首页 > 解决方案 > 在 Python 中使用换行符读取文件

问题描述

需要帮助,我收到一个带有新行的文件。

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

标签: python-3.7

解决方案


这是一种方法

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)

推荐阅读