在 csv 文件中反转行的最佳方法 python

Best way to reverse lines in a csv file python

我想知道在 python 2.7 中反转大型 csv 文件(+50000 行)的行并重写它,避免第一行的最佳方法。

input:
A;B;C
1;2;3
4;5;6

output
A;B;C
4;5;6
1;2;3

我需要知道如何在 python 2.7.

中以有效的方式做到这一点

谢谢大家,

门乔佩斯

阅读如下:

rows = []
first = True
for row in reader:
    if first:
        first = False
        first_row = row
        continue
    rows.append(row)

写成如下:

rows.append(first_row)
writer.writerows(rows[::-1])

如果可以使用外部库,pandas 库适用于大文件:

import pandas as pd

# load the csv and user row 0 as headers
df = pd.read_csv("filepath.csv", header = 0)

# reverse the data
df.iloc[::-1]

如果您不能使用外部库:

import csv

with open("filepath.csv") as csvFile:
    reader = csv.reader(csvFile)


    # get data
    data = [row for row in reader]
    # get headers and remove from data
    headers = data.pop(0)

# reverse the data
data_reversed = data[::-1]

# append the reversed data to the list of headers
output_data = headers.append(data_reversed)

使用 csv 模块读取 csv 文件并使用 csv 模块打开输出。现在您正在使用 lists 作为行。

使用next写标题行as-is。现在第一行被消费了,将其余数据转换为 list 以完全读取它并在反向列表上应用 writerows

import csv

with open("in.csv") as fr, open("out.csv","wb") as fw:
    cr = csv.reader(fr,delimiter=";")
    cw = csv.writer(fw,delimiter=";")
    cw.writerow(next(cr))  # write title as-is
    cw.writerows(reversed(list(cr)))

writerows 是最快的方法,因为它不涉及 python 循环。

Python 3 个用户必须使用 open("out.csv","w",newline="") 打开输出文件。