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

标签 python python-2.7 list

<分区>

我有一个相当大的文件 ~ 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)

我知道这在效率方面看起来不太好,这就是为什么我需要更好的东西,但在搜索不同的解决方案后,我坚持使用这个。

最佳答案

文件是它自己的迭代器。

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

关于python - 如何在 Python 中读取和删除文件中的前 n 行 - 优雅的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42630639/

相关文章:

python - 根据列值确定优先级并选择行

Python; BeautifulSoup 和内置函数

Python:知道函数是从单元测试调用的吗?

python - 使用 Python 2.7 未将数据插入到 Sqlite3 数据库中

r - 如何按矩阵内的行堆叠列表(数据帧或向量)的元素,包括 R 中的列名称?

python - 如何在 Postgresql hstore 中存储 python 字典

python - 如何获取某个区域的像素值?

python - 对内联排序的简单尝试返回 None,不知道为什么

python - 如何使用列表重命名 Pandas 中的列

arrays - F# - 将数组转换为列表