Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove whitespaces from beginning and end of each line in a file in python

I am trying to read some numbers from a file and store them into an array called numbers. I use strip() for each line to remove the \n at the end of each line. I also use split(' ') for each line to remove the spaces between the numbers.

The problem is that in the input file the first character on the line and the last character on the line are spaces. How can I erase them?

This is my code:

def read_from_file():
    f = open('input_file.txt')
    numbers = []
    for eachLine in f:
        line = eachLine.strip()
        for x in eachLine.split(' '):
            line2 = int(x)
            numbers.append(line2)
    f.close()
    print numbers

This is the text file, where the underscores are spaces:

_9 5_
_2 3 1 5 4_
_2 1 5_
_1 1_
_2 1 2_
_2 2 3_
_2 3 4_
_3 3 4 5_
_2 4 5_
_2 1 5_
_3 1 2 5_
like image 301
user1956185 Avatar asked Jan 24 '14 09:01

user1956185


People also ask

How can you remove whitespace characters from the beginning and end of string python?

Use the . strip() method to remove whitespace and characters from the beginning and the end of a string. Use the . lstrip() method to remove whitespace and characters only from the beginning of a string.

Which function is used for removing Whitespaces from beginning and end of the string?

The trim() function removes whitespace and other predefined characters from both sides of a string.

Which function is used for removing Whitespaces from beginning?

Answer : trim. trim function is ussed to remove strip whitespace (or other character) from beginning and end of the string.

Which commands are there to remove Whitespaces?

s/[[:space:]]//g; – as before, the s command removes all whitespace from the text in the current pattern space.


2 Answers

strip() already removes the spaces from both ends. The error is in the line:

for x in eachLine.split(' '):

You should use line and not eachLine in the for.

To avoid this kind of problems you could avoid using the intermediate variable at all:

for line in f:
    for x in line.strip().split():
        # do stuff

Note that calling split() without arguments splits on any sequence of whitespace, which is usually what you want. See:

>>> 'a  b c d'.split()
['a', 'b', 'c', 'd']
>>> 'a  b c d'.split(' ')
['a', '', 'b', 'c', 'd']

Note the empty string of the last result. split(' ') splits on every single whitespace.

like image 50
Bakuriu Avatar answered Oct 29 '22 16:10

Bakuriu


with open("myfile.txt") as lines:
    for line in lines:
        print line.strip()

Use .strip to remove leading and trailing whitespace

like image 24
Jakob Bowyer Avatar answered Oct 29 '22 16:10

Jakob Bowyer