我有一个相当大的文件~1MB大小,我希望能够读取前N行,将它们保存到列表中(新列表)供以后使用,然后删除它们。
我能够这样做:
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)
我知道这在效率方面看起来并不好,这就是为什么我需要更好的东西,但在寻找不同的解决方案后,我一直坚持这个。
答案 0 :(得分:5)
文件是它自己的迭代器。
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")