Skip to main content
 首页 » 编程设计

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

2025年05月04日13java哥

所以我有一个由我的爬虫制作的疯狂的长文本文件,出于某种原因它在链接之间添加了一些空格,如下所示:

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)