用python洗净csv行

时间:2018-11-16 09:28:34

标签: python csv

我只想简单地整理csv文件的行,但将标头保持静态。

unshuffled.csv

的内容
Lastname  Firstname   Age

taylor    bob         40
mcdonald  kevin       32
smith     john        18

想输出到以下的 shuffled.csv

Lastname  Firstname   Age
smith     john        18
mcdonald  kevin       32
taylor    bob         40

我正在使用下面的代码,这是另一篇文章中建议的,但是对我不起作用。

from random import shuffle

with open('unshuffled.csv','r') as ip:
    data=ip.readlines()

    header, rest=data[0], data[1:]

    shuffle(rest)
with open('shuffled.csv','w') as out:
    out.write(''.join([header]+rest))

但是,输出csv会按如下所示在三列之外随机播放数据。

Lastname  Firstname   Age
smith     john        18    32    kevin
taylor    bob         40

如何使列为静态,并仅对csv文件中的行进行混洗。

2 个答案:

答案 0 :(得分:1)

您必须在unshuffled.csv的最后一行缺少换行符,因此请使用以下命令:

import random

with open('unshuffled.csv', 'r') as r, open('shuffled.csv', 'w') as w:
    data = r.readlines()
    header, rows = data[0], data[1:]
    random.shuffle(rows)
    rows = '\n'.join([row.strip() for row in rows])
    w.write(header + rows)

答案 1 :(得分:0)

尝试这样的事情:

from random import shuffle

with open('unshuffled.csv') as ip:
    lines=ip.readlines()
    header = lines.pop(0)
    shuffle(lines)
    lines.insert(0, header)

with open('shuffled.csv','w') as out:
    out.writelines(lines)