首页 > 解决方案 > 与文本文件交互时 Python 3 中 str.split() 的替代方案

问题描述

我目前正在使用 Python 制作文件复制器。当我在实际程序中自定义重复数量时,它目前可以自行工作,但我正在制作一个单独的基本设置文件。这将允许您指定所需的重复次数。

目前,该号码以列表形式保存到纯文本文档中。因此,根据您输入的内容,文档可能看起来像 [0, 1, 2, 3] 到 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]。

问题是,当实际的复制程序试图从纯文本文件中获取列表时,它会将其解释为字符串,所以它看起来像

count = ['[0, 1, 2, 3, 4, 5]']

我已经在互联网上广泛搜索了这个问题的解决方案,但我能找到的唯一解决方案是使用 str.split()。据我所知,这已在 Python 3 中删除。在这种情况下我可以采用什么替代方案?

这是实际复制器的代码:

#!/usr/bin/env python
import shutil
import getpass
data = open("/Volumes/USB/Data.txt", "r")
username = getpass.getuser()
count = data.readlines(1)
print(str(count))
for x in count:
    shutil.copy2('/Volumes/USB/img.jpg', 'img{0}.jpg'.format(x))
    print(str(count))

这是安装文件的代码:

import time
import fileinput
with open("/Volumes/USB/Data,txt", "r") as f:
# Precount is where the original list will go to let them know how many have previously been selected. I will convert this to the number of entries in the list eventually.
    precount = list(f.readlines(1))
    print('Enter the desired amount of images. Your current amount is {0}.'.format(precount))
countbase = input()
count = [0]
n = 1
while int(n) < int(countbase):
    list.append(count, n)
    n += 1
with open("/Volumes/USB/Data.txt", "w") as f:
    f.write(str((count)))
print('Configuration complete!')
time.sleep(1)
quit()

谢谢你的帮助!

标签: pythonpython-3.xlistfile

解决方案


您可能会更满意next(data),但您目前拥有的是由.readlines(1).

如果您采用初始列表元素,您将只有一个字符串:

count[0]

您可以将其传递给 JSON 解析器以将字符串转换为整数列表:

import json
counts = json.loads(count[0])

然后你可以迭代那些ints 到你的心脏的内容。


推荐阅读