在Python中使用换行符读取文件

时间:2019-09-19 02:28:56

标签: python-3.7

需要帮助,我收到带有换行符的文件。

name,age
"Maria",28
"Kevin",30
"Joseph",31
"Faith",20
"Arnel
",21
"Kate",40

如何识别该行并将其从列表中删除?

输出应为

name,age
"Maria",28
"Kevin",30
"Joseph",31
"Faith",20
"Kate",40

1 个答案:

答案 0 :(得分:0)

这是一种方法

import csv

data = []
with open(filename) as infile:
    reader = csv.reader(infile)
    for line in reader:
        if not line[0].endswith("\n"):
            data.append(line)

with open(filename, "w") as outfile:
    writer = csv.writer(outfile)
    writer.writerows(data)

您还可以使用str.strip()更正条目。

例如:

import csv

data = []
with open(filename) as infile:
    reader = csv.reader(infile)
    for line in reader:
        if line[0].endswith("\n"):
            line[0] = line[0].strip() 
        data.append(line)

with open(filename, "w") as outfile:
    writer = csv.writer(outfile)
    writer.writerows(data)