Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all spaces in text file with 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)

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.

like image 858
man Avatar asked Apr 17 '17 07:04

man


2 Answers

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)
like image 76
lch Avatar answered Oct 23 '22 06:10

lch


You can open file and read line by line and remove white space -

Python 3.x:

with open('filename') as f:
    for line in f:
        print(line.strip())

Python 2.x:

with open('filename') as f:
    for line in f:
        print line.strip()

It will remove space from each line and print it.

Hope it helps!

like image 44
Om Prakash Avatar answered Oct 23 '22 07:10

Om Prakash