簡體   English   中英

如何使用python從文本文件中刪除空白空間?

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

文本文件的圖像

現在我想要在這個文本文件中寫成一行的完整文本,這樣它看起來像這樣:我想要它是什么樣的 我如何使用 python 做到這一點? 我嘗試了剝離功能,替換功能等。它不只是工作。

您只需要讀入文件,刪除新行並再次寫入即可。

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