首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >性能- python文本文件编辑2GB文件

性能- python文本文件编辑2GB文件
EN

Stack Overflow用户
提问于 2013-10-19 20:21:24
回答 1查看 229关注 0票数 1

我在python 3中运行以下代码以获取.txt文件,每隔一行编辑一次,并存储已编辑的.txt文件。它对小文件很有用,但是我的文件是2GB的,花费的时间太长了。

有人对如何修改代码以提高效率和速度有任何建议吗?

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-19 21:09:34

我建议你这样做:

代码语言:javascript
复制
# 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))

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

代码语言:javascript
复制
# 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)

所以您不必将文件的全部内容保存在内存中。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19470733

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档