繁体   English   中英

如何使用 Python 删除行

[英]How to Delete rows with 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,

这实际上将删除这些行,而不是用空格替换 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

暂无
暂无

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

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