python - 如何使用 Python 删除行

我需要一点帮助

此脚本将删除行

with open("test1.txt", 'r') as f:
    lines = f.readlines()

to_delete =  ["apnid","apnzid","apncb"]
new_lines = []
for l in lines:
    for d in to_delete:
        if d in l:
            l = "",
            break
    new_lines.append(l)

with open("test2.txt", 'w') as file2:
    file2.writelines(new_lines)

我正在升级到这个

import os

for root, dirs, files in os.walk('Originals\.'):
    for name in files:
        nmin = os.path.join(root,name)
        with open(nmin,"r") as f:
             lines = f.readlines()
             
to_delete = ["apnid","apnzid","apncb"]
new_lines = []
for l in lines:
    for d in to_delete:
        if d in l:
            l = ""
            break
    new_lines.append(l)

with open(nmin,"w") as fout:
    fout.writelines(new_lines)

我运行 Run Module 并没有收到错误

你能帮我找出问题所在吗

该脚本打开 CMD 窗口并立即关闭它不会删除任何行

Before 
      "apnid": -2147483648,
      "apnzid": -2147483648,
      "apncf": -2147483648,
      "apncb": -2147483648,
      "apfid": -2147483648,

Results
      "apncf": -2147483648,
      "apfid": -2147483648,

回答1

这实际上将删除这些行,而不是用空格替换 then:

import os

to_delete = ["apnid","apnzid","apncb"]

for root, dirs, files in os.walk('Originals\.'):
    for name in files:
        nmin = os.path.join(root,name)
        with open(nmin,"r") as f:
             lines = f.readlines()
             
        new_lines = []
        for l in lines:
            for d in to_delete:
                if d in l:
                    break
            else:
                new_lines.append(l)

        with open(nmin,"w") as fout:
            fout.writelines(new_lines)

请注意,构建 new_lines 列表没有特别的原因。您可能只是在循环内执行 write

相似文章