[英]Remove all lines that start with a number using python
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. 您正在整行上调用
is_digit
,仅当该行完全由数字组成时才会返回True
。
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. lstrip().isdigit()
不会检查行中的第一个字符是否为数字。 You should take the first char (if the line has chars) and check isdigit()
on that char: 您应该获取第一个字符(如果该行包含字符),并检查该字符上的
isdigit()
:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.