<分区>
我有一个相当大的文件 ~ 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)
我知道这在效率方面看起来不太好,这就是为什么我需要更好的东西,但在搜索不同的解决方案后,我坚持使用这个。