【问题标题】:Remove white spaces in text file and overwrite inplace删除文本文件中的空格并就地覆盖
【发布时间】:2020-08-13 08:04:41
【问题描述】:

如何检查文本文件中的每一行并删除每行开头的空格?

这是我尝试过的,但它给了我一个空白文件

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

【问题讨论】:

  • 你正在从同一个文件(0. text)读写,open创建一个新文件,使用不同的文件名进行写入。

标签: python list text


【解决方案1】:

如果您想就地更改文件,我建议使用名为 fileinput 的内置模块。

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

请注意,我指定了空的 end,因为这些行已经有尾随换行符。如果您想了解有关该模块的更多信息,我建议您阅读PyMOTW3 article

【讨论】:

    猜你喜欢
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2014-08-07
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多