Sukey
Sukey

Reputation: 21

remove 0 number lines in txt file with python

I have a txt file like this txt

And I want to remove those lines of 0. This is my code which seems doesn't work:

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?

Upvotes: 1

Views: 39

Answers (2)

balderman
balderman

Reputation: 23815

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')

Upvotes: 1

MetallimaX
MetallimaX

Reputation: 614

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)

Upvotes: 1

Related Questions