且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Python从文件中删除空格和空行

更新时间:2023-02-09 13:13:35

strip()删除前导和尾随空格字符.

strip() removes leading and trailing whitespace characters.

with open("transfer-out/" + file, "r") as f:
    for line in f:
        cleanedLine = line.strip()
        if cleanedLine: # is not empty
            print(cleanedLine)

然后,您可以将脚本重定向到例如文件python clean_number.py > file.txt.

Then you can redirect the script into a file python clean_number.py > file.txt, for example.