【问题标题】:Remove new line \n reading from CSV删除从 CSV 读取的新行 \n
【发布时间】:2015-01-26 08:36:05
【问题描述】:

我有一个 CSV 文件,如下所示:

Name1,1,2,3
Name2,1,2,3
Name3,1,2,3

我需要将它逐行读入二维列表。我编写的代码几乎可以完成这项工作;但是,我在删除第三个索引末尾的换行符 '\n' 时遇到问题。

    score=[]

    for eachLine in file:
            student = eachLine.split(',')
            score.append(student)
    print(score)

目前的输出如下:

[['name1', '1', '2', '3\n'], ['name2', '1', '2', '3\n'],

我需要它看起来像:

[['name1', '1', '2', '3'], ['name2', '1', '2', '3'],

【问题讨论】:

  • 我已经使用阅读器完成了。只是想看看我还能做些什么 - 学习!

标签: python list csv


【解决方案1】:

在处理它们时只需在每一行上调用str.strip

score=[]

for eachLine in file:
        student = eachLine.strip().split(',')
        score.append(student)
print(score)

【讨论】:

    【解决方案2】:

    你可以使用splitlines

    第一种方法

    >>> s = '''Name1,1,2,3
    ... Name2,1,2,3
    ... Name3,1,2,3'''
    >>> [ item.split(',') for item in s.splitlines() ]
    [['Name1', '1', '2', '3'], ['Name2', '1', '2', '3'], ['Name3', '1', '2', '3']]
    

    第二种方法

    >>> l = []
    >>> for item in s.splitlines():
    ...     l.append(item.split(','))
    ... 
    >>> l
    [['Name1', '1', '2', '3'], ['Name2', '1', '2', '3'], ['Name3', '1', '2', '3']]
    

    【讨论】:

      【解决方案3】:

      如果你知道它是一个\n,而且只有一个\n,

      score=[]
      
      for eachLine in file:
              student = eachLine[:-1].split(',')
              score.append(student)
      print(score)
      

      在拆分发生之前使用切片删除尾随的换行符。

      已编辑,根据评论者的建议;)更整洁。

      【讨论】:

      • 为什么不直接使用strip?如果你要切片,为什么不[0:-1]
      • @jonrsharpe,我会说不是 [:-1]
      • 无法告诉你为什么或为什么不脱衣。我想我个人只是喜欢更具体地了解我的对象会发生什么。我知道,我没有将我的字符串留给(大量且有据可查的)strip 函数的命运,而这只是一个结束。没有惊喜(不应该有任何惊喜,使用条带)。称之为怪癖?会有性能差异吗? @jonrsharpe?
      • 我希望切片速度更快(timeit 建议在'foo\n' 上快两倍),但如果您剪切的文件末尾没有空行最后一行的最后一个字符。此外,strip 更传统,因此阅读它的脑力消耗更少。
      • 关于对所需数据的潜在切片的好点@jonrsharpe,必须小心
      【解决方案4】:

      使用 rstrip 函数识别每行末尾的 \n 并将其删除。 请参阅下面的代码以供参考。

      with open('myfile.csv', 'wb') as file: 
          for line in file:
              line.rstrip('\n')
              file.write(line)
      

      【讨论】:

      • 为什么不只是rstrip()strip()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 2018-08-15
      • 2021-12-18
      • 1970-01-01
      • 2021-09-17
      • 2021-09-07
      相关资源
      最近更新 更多