从CSV移除新行\ n阅读 [英] Remove new line \n reading from CSV

查看:55
本文介绍了从CSV移除新行\ n阅读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a CSV file which looks like:

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

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

I need to read it into a 2D list line by line. The code I have written almost does the job; however, I am having problems removing the new line characters '\n' at the end of the third index.

    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'],

推荐答案

只需调用

simply call str.strip on each line as you process them:

score=[]

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

这篇关于从CSV移除新行\ n阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆