【发布时间】:2013-10-19 20:21:24
【问题描述】:
我在 python 3 中运行以下代码以获取 .txt 文件,每隔一行编辑一次,并存储编辑后的 .txt 文件。它适用于小文件,但我的文件约为 2GB,而且需要的时间太长。
是否有人对如何更改代码以提高效率和速度有任何建议?
newData = ""
i=0
run=0
j=0
k=1
seqFile = open('temp100.txt', 'r')
seqData = seqFile.readlines()
while i < 14371315:
sLine = seqData[j]
editLine = seqData[k]
tempLine = editLine[0:20]
newLine = editLine.replace(editLine, tempLine)
newData = newData + sLine + newLine
if len(seqData[k]) > 20:
newData += '\n'
i=i+1
j=j+2
k=k+2
run=run+1
print(run)
seqFile.close()
new = open("new_temp100.txt", "w")
sys.stdout = new
print(newData)
【问题讨论】:
-
您可能应该创建一个字符串列表然后
''.join(strings)它们,而不是循环和+=ing。见stackoverflow.com/a/1967732/600110。 -
你的缩进不正确
标签: python performance text