简体   繁体   English

如何从文本文件中删除特定行?

[英]How do I remove a specific line out of a text file?

file = open(userid, "r+") 
#userid is in the form
# A
# B
# C
# etc...
removeRead = file.readlines()
del removeRead[int(index)]
file.write(str(removeRead))

This is what I've tried so far.这是我迄今为止尝试过的。 Ive looked at other questions asking this and one of the suggestions was to 'simply iterate over the whole file and write all the lines except the one you want to remove` with their suggestion being我查看了其他问题,其中一个建议是“简单地遍历整个文件并编写除要删除的行之外的所有行”,他们的建议是

with open('fordel.txt') as f, open('out.txt', 'w') as fo:
    for linenum, line in enumerate(f, start=1):
        if linenum != badline:
            fo.write(line)
    # obviously not to my code

Is this really the simplest solution (ie does python really not have an inbuilt solution for this?), and how exactly does it work so I can implement it into my code?这真的是最简单的解决方案吗(即 python 真的没有内置的解决方案吗?),它究竟是如何工作的,所以我可以将它实现到我的代码中?

I am not sure if you require the enumerate() as that is to keep track/count of the number of lines, you could use if you really knew the line at which you want to remove some specific line, but this a maybe simpler variation, give it a shot:我不确定您是否需要enumerate()来跟踪/计算行数,如果您真的知道要删除某些特定行的行,则可以使用它,但这可能是一个更简单的变体, 试一试:

  with open("originalfile.txt", "r") as currentfile:
    with open("finalfile.txt", "w") as endfile: 
      for line in currentfile:
        if line.strip("\n") != "the line you want to delete":
           endfile.write(line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM