【问题标题】:Remove whitespaces from beginning and end of each line in a file in python从python中的文件中的每一行的开头和结尾删除空格
【发布时间】:2014-01-24 17:31:05
【问题描述】:

我正在尝试从文件中读取一些数字并将它们存储到名为numbers 的数组中。 我对每一行使用strip() 来删除每行末尾的\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

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

_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_

【问题讨论】:

    标签: python file removing-whitespace


    【解决方案1】:

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

    for x in eachLine.split(' '):
    

    您应该在for 中使用line 而不是eachLine

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

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

    请注意,在没有参数的情况下调用split() 会在任何 空格序列上拆分,这通常是您想要的。见:

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

    注意最后一个结果的空字符串。 split(' ') 在每个单个空白处分割。

    【讨论】:

    • 您可以使用for line in (line.strip() for line in f):,因此无需在循环中进行剥离。
    • @Bakuriu 我已经更改了我的代码,以便不使用中间变量,并且我已将split(' ') 更改为split()。现在它可以正常工作了。谢谢
    【解决方案2】:
    with open("myfile.txt") as lines:
        for line in lines:
            print line.strip()
    

    使用.strip 删除前导和尾随空格

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-22
      • 2023-04-09
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      相关资源
      最近更新 更多