在python中删除文件中每行开头和结尾的空格

use*_*185 5 python file removing-whitespace

我试图从文件中读取一些数字并将它们存储到一个名为numbers. 我使用strip()for 每行删除\n每行末尾的 。我还使用split(' ')每一行来删除数字之间的空格。

问题是在输入文件中,该行的第一个字符和该行的最后一个字符是空格。我怎样才能擦除它们?

这是我的代码:

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
Run Code Online (Sandbox Code Playgroud)

这是文本文件,其中下划线是空格:

_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_
Run Code Online (Sandbox Code Playgroud)

Bak*_*riu 4

strip()已经删除了两端的空格。错误在行中:

for x in eachLine.split(' '):
Run Code Online (Sandbox Code Playgroud)

您应该使用lineand 而不是eachLinefor.

为了避免此类问题,您可以完全避免使用中间变量:

for line in f:
    for x in line.strip().split():
        # do stuff
Run Code Online (Sandbox Code Playgroud)

请注意,split()不带参数的调用会在任何空白序列上进行分割,这通常是您想要的。看:

>>> 'a  b c d'.split()
['a', 'b', 'c', 'd']
>>> 'a  b c d'.split(' ')
['a', '', 'b', 'c', 'd']
Run Code Online (Sandbox Code Playgroud)

请注意最后结果的空字符串。在每个split(' ')空格上进行分割。