Deleting a line from a text file

泪湿孤枕 提交于 2019-11-28 02:28:03

Use the fileinput module's inplace functionality. Refer Optional in-place filtering section at fileinput. The example below deletes the first line from a file:

import fileinput
import sys

for line_number, line in enumerate(fileinput.input('myFile', inplace=1)):
  if line_number == 0:
    continue
  else:
    sys.stdout.write(line)
nico

You cant delete a line from a file (or in very specific condition)

I would try to rewrite (in another file) all the content but the line, and then replace the original file with the new one.

This option only works if file is reasonnably small.

Deleting a specific line in a file (python)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!