所以我有个问题。我正在使用.txt文件,它由多个4行组成。我在Python3中工作。在
我写了一个代码,它的意思是每2行和第4行取一个文本文件,只保留这两行的前20个字符(而不编辑第1行和第3行),并创建一个新的编辑文件,其中包括已编辑的第2行和第4行以及未编辑的第1行和第3行。这个趋势对于每一行都是一样的,因为我使用的所有文本文件的行号总是4的倍数。在
这对小文件(总共约100行)有效,但我需要编辑的文件有5000多万行,需要4个多小时。在
下面是我的代码。有谁能给我一个关于如何加快我的计划的建议吗?谢谢!在
import io
import os
import sys
newData = ""
i=0
run=0
j=0
k=1
m=2
n=3
seqFile = open('temp100.txt', 'r')
seqData = seqFile.readlines()
while i < 14371315:
sLine1 = seqData[j]
editLine2 = seqData[k]
sLine3 = seqData[m]
editLine4 = seqData[n]
tempLine1 = editLine2[0:20]
tempLine2 = editLine4[0:20]
newLine1 = editLine2.replace(editLine2, tempLine1)
newLine2 = editLine4.replace(editLine4, tempLine2)
newData = newData + sLine1 + newLine1 + '\n' + sLine3 + newLine2
if len(seqData[k]) > 20:
newData += '\n'
i=i+1
run=run+1
j=j+4
k=k+4
m=m+4
n=n+4
print(run)
seqFile.close()
new = open("new_100temp.txt", "w")
sys.stdout = new
print(newData)
如果一次只读取4行并处理这些行(未经测试),可能会快得多:
其中
grouper(it, n)
是一个一次生成iterabelit
项的函数。它是作为itertools
模块的examples之一给出的(另请参见this anwerat SO)。以这种方式迭代文件类似于在文件上调用readlines()
,然后手动迭代得到的列表,但它一次只向内存中读入几行。在您正在处理内存中的两个文件(输入和输出)。如果文件太大(分页),可能会导致时间问题。Try(伪代码)
这里最大的问题似乎是一次读取整个文件:
seqData = seqFile.readlines()
相反,您应该首先打开源文件和输出文件。然后在第一个文件上进行迭代,并根据需要操作行:
相关问题 更多 >
编程相关推荐