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

发布于 2021-01-29 16:41:41

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

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

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

关注者
0
被浏览
45
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    似乎您无法直接编辑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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看