Reputation: 2772
I am trying to remove all lines in a file that starts with numbers. I came up with that block of code below but it's not working.
output = open("/home/test1/Desktop/diff2.txt", "w")
with open("/home/test1/Desktop/diff.txt") as input:
for line in input:
if not line.lstrip().isdigit():
output.write(line)
print(line)
input.close()
output.close()
exit();
It still ends up printing all lines that start with numbers in the output file
Upvotes: 0
Views: 1245
Reputation: 11602
You are calling is_digit
on the whole line, which will return True
only if the line consists entirely of digits.
with open('input.txt') as inp, open('output.txt', 'w') as out:
out.write(''.join(l for l in inp if l[0] not in '123456789'))
Upvotes: 0
Reputation: 4161
This following script works fine on my quick test case:
output = open("test.out", "w")
with open("test.in") as input:
for line in input:
if not line.lstrip()[0].isdigit():
output.write(line)
print(line)
output.close()
With input:
1test
2test
hello
3test
world
4something
Gives output:
hello
world
Upvotes: 2
Reputation: 62566
The lstrip().isdigit()
doesn't check the first char in your line is a digit. You should take the first char (if the line has chars) and check isdigit()
on that char:
if line == '' or not line[0].isdigit():
output.write(line)
Upvotes: 1