如何在Python中读取和删除文件中的前n行 - 优雅解决方案

Ste*_*wer 3 python list python-2.7

我有一个相当大的文件〜1MB大小,我希望能够读取第一个N行,将它们保存到一个列表(newlist供以后使用),然后将其删除.

我能够这样做:

import os

n = 3 #the number of line to be read and deleted

with open("bigFile.txt") as f:
    mylist = f.read().splitlines()

newlist = mylist[:n]
os.remove("bigFile.txt")

thefile = open('bigFile.txt', 'w')

del mylist[:n]

for item in mylist:
  thefile.write("%s\n" % item)
Run Code Online (Sandbox Code Playgroud)

我知道这在效率方面看起来不太好,这就是为什么我需要更好的东西,但在寻找不同的解决方案后,我一直坚持这个.

bru*_*ers 6

文件是它自己的迭代器.

n = 3
nfirstlines = []

with open("bigFile.txt") as f, open("bigfiletmp.txt", "w") as out:
    for x in xrange(n):
        nfirstlines.append(next(f))
    for line in f:
        out.write(line)

# NB : it seems that `os.rename()` complains on some systems
# if the destination file already exists.
os.remove("bigfile.txt")
os.rename("bigfiletmp.txt", "bigfile.txt")
Run Code Online (Sandbox Code Playgroud)

  • 它看起来像 Python 3.3+ `os.remove("bigfile.txt"); os.rename("bigfiletmp.txt", "bigfile.txt")` 可以简化为 `os.replace("bigfiletmp.txt", "bigfile.txt")`。 (3认同)