python操作大文件删除某行

删掉文件其中一行,非常简单,不过如果一个文件很大以至于无法读到内存里,又该怎么操作呢 其实我们可以使用 open() 方法把需要修改的文件打开为两个文件,然后逐行读入内存,找到需要删除的行...

删掉文件其中一行,非常简单,不过如果一个文件很大以至于无法读到内存里,又该怎么操作呢

其实我们可以使用 open() 方法把需要修改的文件打开为两个文件,然后逐行读入内存,找到需要删除的行时,用后面的行逐一覆盖,具体代码为:

#输入你需要删除的行数,例如这里是第六行
del_numb=6
with open('file.txt', 'r') as old_file:
with open('file.txt', 'r+') as new_file:
current_line = 0
# 定位到需要删除的行
while current_line < (del_numb-1):
old_file.readline()
current_line += 1
# 当前光标在被删除行的行首,记录该位置
seek_point = old_file.tell()
# 设置光标位置
new_file.seek(seek_point, 0)
# 读需要删除的行,光标移到下一行行首
old_file.readline()
# 被删除行的下一行读给 next_line
next_line = old_file.readline()
# 连续覆盖剩余行,后面所有行上移一行
while next_line:
new_file.write(next_line)
next_line = old_file.readline()
new_file.truncate()

相关链接:https://blog.csdn.net/qq_31135027/article/details/78908559

  • 发表于 2022-10-24 16:10
  • 阅读 ( 919 )
  • 分类:python

你可能感兴趣的文章

0 条评论

请先 登录 后评论
xun
xun

电路元件工程师

66 篇文章

作家榜 »

  1. omicsgene 654 文章
  2. 安生水 325 文章
  3. Daitoue 167 文章
  4. 生物女学霸 120 文章
  5. 红橙子 78 文章
  6. CORNERSTONE 72 文章
  7. rzx 67 文章
  8. xun 66 文章