using Python for deleting a specific line in a fil

2018-12-31 06:26发布

Let's say I have a text file full of nicknames. How can I delete a specific nickname from this file, using Python?

14条回答
墨雨无痕
2楼-- · 2018-12-31 07:18

Solution to this problem with only a single open:

f = open("target.txt","r+")
d = f.readlines()
f.seek(0)
for i in d:
    if i != "line you want to remove...":
        f.write(i)
f.truncate()
f.close()

This solution opens the file in r/w mode ("r+") and makes use of seek to reset the f-pointer then truncate to remove everything after the last write.

查看更多
无色无味的生活
3楼-- · 2018-12-31 07:21

The issue with reading lines in first pass and making changes (deleting specific lines) in the second pass is that if you file sizes are huge, you will run out of RAM. Instead, a better approach is to read lines, one by one, and write them into a separate file, eliminating the ones you don't need. I have run this approach with files as big as 12-50 GB, and the RAM usage remains almost constant. Only CPU cycles show processing in progress.

查看更多
登录 后发表回答