使用 Python 3.x 删除文本文件中的所有空格 [英] Removing all spaces in text file with Python 3.x

查看:25
本文介绍了使用 Python 3.x 删除文本文件中的所有空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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                                (note the spaces)
https://example.com/johndoe.php                              (again)

我想摆脱它,但保留新行.请记住,文本文件有 4.000 多行长.我试着自己做,但我不知道如何遍历文件中的新行.

I want to get rid of that, but keep the new line. Keep in mind that the text file is 4.000+ lines long. I tried to do it myself but figured that I have no idea how to loop through new lines in files.

推荐答案

好像不能直接编辑python文件,所以我的建议是:

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)

这篇关于使用 Python 3.x 删除文本文件中的所有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆