简体   繁体   English

使用 python 删除 txt 文件中的 0 行

[英]remove 0 number lines in txt file with python

I have a txt file like this txt我有一个像这样的txt文件

And I want to remove those lines of 0. This is my code which seems doesn't work:我想删除那些 0 行。这是我的代码,它似乎不起作用:

ifn = r"C:\Users\sukey\Documents\560\hw4\Results\sim_seconds.txt"
ofn = r"C:\Users\sukey\Documents\560\hw4\Results\new.txt"
infile = open(ifn,'r')
outfile = open(ofn,'w')
lines = infile.readlines()
for l in lines:
    if l != "0":
        outfile.write(l)

How can I fix it?我该如何解决?

Try this:尝试这个:

ifn = r"C:\Users\sukey\Documents\560\hw4\Results\sim_seconds.txt"
ofn = r"C:\Users\sukey\Documents\560\hw4\Results\new.txt"
with open(ifn,'r') as infile:
    with open(ofn,'w') as outfile:
        for l in infile.readlines():
            if l != "0\n":
                outfile.write(l)

something like the below类似于下面的东西

with open('in.txt') as f_in:
    lines = [l.strip() for l in f_in.readlines()]
    with open('out.txt', 'w') as f_out:
        for line in lines:
            if line != "0":
                f_out.write(line + '\n')

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

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