python-3.7 - 在 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
解决方案
这是一种方法
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)
推荐阅读
- cluster-analysis - 如何从 vis.js 中删除集群
- android - 如何从类中的方法通过 FirebaseFirestore 查询检索数据列表?
- javascript - 先前声明的对象内的 Javascript 函数():“被调用”事件?
- html - 如何相对于上部图像定位另一个图像
- python - Pandas - 多轴上 groupby() 上的 cumsum()
- javascript - 在 Odoo 12 的向导中单击取消后如何返回主页?
- python - 创建一个从用户获取输入并检查负值的 while 循环
- typescript - 我无法理解如何用 typerscript 语言定义 xpath 的语法
- python - 改组大型内存映射的numpy数组
- python - Python Openpyxl - 在 write_only 电子表格中添加列