簡體   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