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

10,356

Solution 1

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.

Solution 2

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

Use .strip to remove leading and trailing whitespace

Share:
10,356
user1956185
Author by

user1956185

Updated on June 22, 2022

Comments

  • user1956185
    user1956185 about 2 years

    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_