python - 如何从最后一行读取行?
问题描述
我想从最后一个到第一个读取行。但我不能这样做。我想以相反的顺序阅读。
stary_patient_2 ='Xs'
nowy_patient_2 = 'VB'
import csv
with open(DATA_DIR+'/stage_2_train_labels_right.csv', 'r') as inp, open(DATA_DIR+'/stage_2_train_labels_right_poprawne.csv', 'w') as out:
reader = csv.DictReader(inp, delimiter=' ',fieldnames = ['patientId','x', 'y', 'width', 'height', 'Target'])
writer = csv.DictWriter(out, fieldnames=reader.fieldnames)
writer.writeheader()
for row in reversed(list(open(DATA_DIR+'/stage_2_train_labels_right.csv'))):
nowy_patient_2 = row[0]
print(row)
print(row[5])
if not (row[5]=='0' and nowy_patient_2==stary_patient_2):
writer.writerow({'patientId': row[0], 'x': row[1], 'y': row[2], 'width': row[3], 'height': row[4], 'Target': row[5]})
stary_patient_2 = nowy_patient_2
输入文件:
asdasd 1 2 3 4 5
dddddd 2 2 2 2 2
cccccc 3 2 5 6 1
输出
cccccc 3 2 5 6 1
dddddd 2 2 2 2 2
asdasd 1 2 3 4 5
解决方案
for row in reversed(list(open(DATA_DIR+'/stage_2_train_labels_right.csv'))):
这是行不通的,因为您再次打开输入文件,然后您没有传递csv
对象而是传递文件句柄。
只需转换reader
为 alist
以完全读取文件,然后您就可以应用于reversed
行列表。
with open(os.path.join(DATA_DIR,'stage_2_train_labels_right.csv'), newline="") as inp, open(os.path.join(DATA_DIR,'stage_2_train_labels_right_poprawne.csv'), 'w', newline="") as out:
reader = csv.DictReader(inp, delimiter=' ',fieldnames = ['patientId','x', 'y', 'width', 'height', 'Target'])
writer = csv.DictWriter(out, fieldnames=reader.fieldnames)
# read input file fully into a list of rows
reader = list(reader)
writer.writeheader()
# now iterate on reversed list
for row in reversed(reader):
推荐阅读
- python-3.x - Scrapy Spider 给出处理错误和最近的回调
- asp.net-core - Blazor WebAssembly AuthenticationState 的标识为空
- python - 提高 pytesseract 中 OCR 处理的速度
- docker - 撰写文件必须是相同的版本 | ECS 命令行 | 码头工人撰写
- flutter - 实施建议并选择它作为firestore?
- python - 如何从两个目录导入图像数据集并为训练和测试添加标签?
- delphi - 什么是 Win10 通知图标/BalloonTipText max。长度
- sql - 如何将动态 SQL 查询输出到 SQL Server 中声明的变量中?
- flutter - 在 Flutter 中实现 RFID 的方法/步骤
- r - 获取用于填充下一行中缺失值的最新可用值 R