使用Python 3.x删除文本文件中的所有空格


问题内容

因此,我的抓取工具制作了一个疯狂的长文本文件,由于某种原因,它在链接之间添加了一些空格,如下所示:

https://example.com/asdf.html                                (note the spaces)
https://example.com/johndoe.php                              (again)

我想摆脱这一点,但要保留新行。请记住,文本文件的长度为4.000+行。我尝试自己做,但是发现我不知道如何在文件中的新行之间循环。


问题答案:

似乎您无法直接编辑python文件,所以这是我的建议:

# first get all lines from file
with open('file.txt', 'r') as f:
    lines = f.readlines()

# remove spaces
lines = [line.replace(' ', '') for line in lines]

# finally, write lines in the file
with open('file.txt', 'w') as f:
    f.writelines(lines)