Removing all spaces in text file with Python 3.x

前端 未结 3 490
日久生厌
日久生厌 2021-01-14 12:33

So I have this crazy long text file made by my crawler and it for some reason added some spaces inbetween the links, like this:

https://example.com/asdf.html         


        
3条回答
  •  误落风尘
    2021-01-14 13:12

    Seems like you can't directly edit a python file, so here is my suggestion:

    # 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)
    

提交回复
热议问题