python - 与文本文件交互时 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()
谢谢你的帮助!
解决方案
您可能会更满意next(data)
,但您目前拥有的是由.readlines(1)
.
如果您采用初始列表元素,您将只有一个字符串:
count[0]
您可以将其传递给 JSON 解析器以将字符串转换为整数列表:
import json
counts = json.loads(count[0])
然后你可以迭代那些int
s 到你的心脏的内容。
推荐阅读
- java - ^= 在 Java for 循环中是什么意思?
- vue.js - VueMapbox 试图创建多个标记
- python - python中字符串firestore之前的几个F&Q 开发一个好的数据库?
- tensorflow - 如何使用手机摄像头实现图像识别
- javascript - ASP.net core MVC 部分视图未卸载 JS
- javascript - 单击按钮 [React] 显示数组中的随机字符串
- python - 循环中迭代文本文件的 Python 函数仅适用于第一个文件
- java - 解决java.lang.NoClassDefFoundError?
- protocol-buffers - 在原型中,如何将地图定义为自定义选项
- entity-framework-core - 如何将影子属性添加到自有类型?