【问题标题】:performance - python text file edit 2GB files性能——python文本文件编辑2GB文件
【发布时间】: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)

【问题讨论】:

标签: python performance text


【解决方案1】:

我会建议这样的事情:

# if python 2.x
#from itertools import tee, izip
# if python 3
from itertols import tee
# http://docs.python.org/2/library/itertools.html#recipes
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    # if python 2.x
    #return izip(a, b)
    return zip(a, b)

new_data = []
with open('temp100.txt', 'r') as sqFile:
    for sLine, edit_line  in pairwise(seqFile):
        # I think this is just new_line = tempLine
        #tempLine = edit_line[:20]
        #new_line = editLine.replace(editLine, tempLine)
        new_data.append(sLine + editLine[:20])
        if len(sLine) > 20:
            new_data.append('\n')



with open("new_temp100.txt", "w") as new:
    new.write(''.join(new_data))

如果您直接流式传输到磁盘,您可能会做得更好

# if python 2.x
#from itertools import tee, izip
# if python 3
from itertols import tee
# http://docs.python.org/2/library/itertools.html#recipes
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    # if python 2.x
    #return izip(a, b)
    return zip(a, b)

new_data = []
with open('temp100.txt', 'r') as sqFile:
    with open("new_temp100.txt", "w") as new:
        for sLine, edit_line  in pairwise(seqFile):
            tmp_str = sLine + editLine[:20]
            if len(sLine) > 20:
                tmp_str = tmp_str + '/n'
            new.write(tmp_str)

因此您不必将文件的全部内容保存到内存中

【讨论】:

  • 为什么要打开一个文件来读取添加内容到一个字符串,然后将其全部写入一个文件?您可以通过嵌套两个打开的调用同时执行这两项操作——然后您只需一次编写每个结果行。认为这会更快。
  • @TimDiggins 因为这就是 OP 所做的(通过重置 sys.stdout = new
  • 嗯,很有趣。但我收到以下错误: from itertools import izip ImportError: cannot import name izip
  • @TomAnonymous 查看编辑,您使用的是 python 3,其中 zip 的行为与 python2 中的 izip 相同。我用python2,这些东西都忘了。
  • 好的,我应用了编辑并修复了错误问题。输出文本出现故障,但我可以自己处理。再次感谢!
猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
相关资源
最近更新 更多