繁体   English   中英

使用python删除所有以数字开头的行

[英]Remove all lines that start with a number using python

我正在尝试删除以数字开头的文件中的所有行。 我想出了下面的代码块,但是它不起作用。

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();

它仍然最终打印输出文件中所有以数字开头的行

您正在整行上调用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'))

lstrip().isdigit()不会检查行中的第一个字符是否为数字。 您应该获取第一个字符(如果该行包含字符),并检查该字符上的isdigit()

if line == '' or not line[0].isdigit():
    output.write(line)

以下脚本可在我的快速测试案例中正常工作:

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

有输入:

1test
2test
hello
3test
world
4something

给出输出:

hello
world

暂无
暂无

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

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