【问题标题】:Deleting a line from txt file从txt文件中删除一行
【发布时间】:2017-12-11 01:23:33
【问题描述】:

我有一个包含类似名称列表的 txt 文件

Name1
Name2
Name3

如果 Name2 在列表中,我想删除其中包含“Name2”的行。我得到了这个代码:

f = open(list,'r')
    if("Name2" in f.read().splitlines()):
        lines = f.readlines()
        f.close()
        f = open(badhumanslist, "w")
        for line in lines:
            if line != "Name2" + "\n":
                f.write(line)
        f.close()

问题是这段代码清空了整个文件。我没有看到我的错误,它应该重写所有行,除了带有“Name2”的那一行

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    您已经阅读了第 2 行中的整个文件:f.read()。然后,lines = f.readlines() 返回一个空列表。

    def read_all():
        with open(filename, "r") as file:
            return file.read()
    content = read_all()
    lines = content.splitlines()
    if "Name2\n" in lines:
        with open(filename, "w") as file:
            for line in lines:
                if line != "Name2\n":
                    file.write(line)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多