python-3.x - 如何在 python 中打乱带有标题的非常大的 .csv 文件?

标签 python-3.x linux bash csv shuffle

基于this发布,使用 shuf 是最快的方法:

import sh
sh.shuf("words.txt", out="shuffled_words.txt")

但是,此代码也会打乱 header 。我的文件有一个 header ,但我不希望 header 在数据中随机播放。

最佳答案

将文件内容复制到另一个不带标题的文件中:

with open("words.txt") as infile, open("words-nohead.txt", "w") as outfile:
    for i,line in enumerate(infile):
        if i: outfile.write(line)

然后打乱 headless 文件。然后将第一个文件的第一行和 headless 文件复制到 shuffled_words.txt 中(我认为您可以使用 sh.cat() 来实现此目的)并删除临时文件。

实际上,您不需要 Python 来实现此目的。单独 Bash 就足够了:

head -n 1 words.txt > shuffled_words.txt    
tail -n+2 words.txt | shuf >> shuffled_words.txt

请记住,无论如何,shuf 都会读取内存中的整个文件。您必须有足够的内存来容纳该文件。

关于python-3.x - 如何在 python 中打乱带有标题的非常大的 .csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68340750/

相关文章:

linux - Upstart 和 uWSGI,工作进程未退出

linux - 输出到文件时得到额外的行?

python - 如何按字典顺序(按计数器,然后按值)对 Counter.mostCommon(n) 的结果进行排序?

python - 选择字符串插值中的小数点位数

python - 在 python3.3 中导入 docx 时出现错误 ImportError : No module named 'exceptions'

linux - 有没有办法将时间命令的输出通过管道传输到日志文件中?

python - 为什么不能在 f 字符串中使用 "await"?

linux - 对返回状态代码 shell 脚本的使用感到困惑?

linux - 使用 awk 根据条件打印特定列

linux - 如何打印命令的结果以及结果的计数?