【问题标题】:Remove lines from file what called from list从文件中删除从列表中调用的行
【发布时间】:2021-03-21 09:57:06
【问题描述】:

我想从 .txt 文件中删除行。 我想为要删除的字符串列出一个列表,但代码会多次粘贴这些行 列表中的尽可能多的字符串。如何避免?

file1 = open("base.txt", encoding="utf-8", errors="ignore") 
Lines = file1.readlines()
file1.close()

not_needed = ['asd', '123', 'xyz']
row = 0

result = open("result.txt", "w", encoding="utf-8")
for line in Lines:
    for item in not_needed:
        if item not in line:
            row += 1
            result.write(str(row) + ": " + line)

所以如果该行包含列表中的字符串,则将其删除。 在每个字符串之后打印不带行的文件。 怎么做?

【问题讨论】:

    标签: python list file


    【解决方案1】:

    查看for 循环中的逻辑... 它的作用是:获取lines 中的每一行,然后所有 not_needed 中的项目通过该行并如果条件得到验证,则写入。但是每次找不到该项目时,条件都会进行验证。 试着考虑做相反的事情:

    • 检查是否不需要某行。
    • 如果什么都不做
    • 否则写

    【讨论】:

    • 我更改了 for line in Lines:for item in not_needed 但仍然在 NotNeeded 中写入尽可能多的字符串
    • link 但我应该是什么样子?
    • 您仍然使用与以前相同的逻辑。见下文。
    【解决方案2】:

    扩展答案

    这就是我认为您正在寻找的东西:

    for line in Lines: 
       if item not in not_needed:
          row += 1
          result.write(str(row) + ": " + line)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      相关资源
      最近更新 更多