首页 > 解决方案 > 如何从最后一行读取行?

问题描述

我想从最后一个到第一个读取行。但我不能这样做。我想以相反的顺序阅读。

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

标签: pythoncsv

解决方案


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):

推荐阅读