【问题标题】:How to read and delete first n lines from file in Python - Elegant Solution [duplicate]如何在 Python 中读取和删除文件中的前 n 行 - 优雅的解决方案 [重复]
【发布时间】:2017-07-26 14:51:07
【问题描述】:

我有一个非常大的文件,大小约为 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)

我知道这在效率方面看起来不太好,这就是为什么我需要更好的解决方案,但在搜索了不同的解决方案后,我被这个解决方案卡住了。

【问题讨论】:

  • 您的意思是要删除文件的第一行?
  • 你几乎被卡住了。如果不重写其后的所有内容,就无法从文件的开头删除。
  • @MarkTolonen 该问题的第二个答案显示了一种更有效的方法。
  • @MarkTolonen 这是同一个问题,我认为可以公平地假设原始问题也需要一种有效的方法
  • 我已标记为重复但发布了答案,因为当前的解决方案对我来说有点弱。

标签: python python-2.7 list


【解决方案1】:

文件是它自己的迭代器。

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")

【讨论】:

  • os.rename 将崩溃,因为目标文件存在。
  • [错误 183] 当文件已存在时无法创建文件
  • @Jean-FrançoisFabre 它不在我的系统上(python 2.7.6,ubuntu 14.04)。
  • 使用os.remove() 调用编辑的代码。
  • 看起来使用 Python 3.3+ os.remove("bigfile.txt"); os.rename("bigfiletmp.txt", "bigfile.txt") 可以精简到 os.replace("bigfiletmp.txt", "bigfile.txt")。
猜你喜欢
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多