简体   繁体   English

如何使用python从文本文件中删除空白空间?

[英]How to delete empty space from a text file using python?

Image of the text file文本文件的图像

Now what I want in this text file is the complete text written in a single line so that it looks like this one: What I want it to be like How do I do this using python?现在我想要在这个文本文件中写成一行的完整文本,这样它看起来像这样:我想要它是什么样的 我如何使用 python 做到这一点? I tried strip function ,replace function etc. It isnt just working.我尝试了剥离功能,替换功能等。它不只是工作。

You just need to read the file in, remove the new lines and write it again.您只需要读入文件,删除新行并再次写入即可。

with open("./foo.txt", "r") as f:
    formatted = ""
    for line in f.readlines():
        formatted += line.replace('\n', " ") # Removes the new lines, add spaces instead
    
    formatted.replace("  ", " ") # Replace double space with one space
    
    # Writes single line to textfile
    with open("./bar.txt", "w") as out:
        out.write(formatted)

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

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