简体   繁体   English

删除文本文件中的空格并就地覆盖

[英]Remove white spaces in text file and overwrite inplace

How to check every line in a text file and remove white spaces at the beginning of each line?如何检查文本文件中的每一行并删除每行开头的空格?

Here is what I tried, but it gives me a blank file instead这是我尝试过的,但它给了我一个空白文件

with open("0.txt","r") as readfile, open("0.txt","w") as outfile:
    for line in readfile:
        if line.startswith(' '):
            outfile.write(line.replace(' ', '')) 

If you want to change file in-place I suggest using built-in module named fileinput .如果您想就地更改文件,我建议使用名为fileinput的内置模块。

import fileinput 
for line in fileinput.input("0.txt", inplace=True):
    print(line.lstrip(), end="")

Note that I specified empty end as these lines already have trailing newlines.请注意,我指定了空end ,因为这些行已经有尾随换行符。 If you want to know more about that module I suggest reading PyMOTW3 article .如果您想了解有关该模块的更多信息,我建议您阅读PyMOTW3 文章

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

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