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
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'))
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.