社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何洗牌非常大。python中带有标题的csv文件?

khemedi • 3 年前 • 1341 次点击  

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

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

然而,这段代码也会洗牌标题。我的文件有一个头,我不想让头在数据中乱放。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130857
 
1341 次点击  
文章 [ 1 ]  |  最新文章 3 年前
DYZ
Reply   •   1 楼
DYZ    4 年前

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

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

然后洗牌无头文件。然后将第一个文件的第一行和无头文件复制到无序的单词中。txt(我想你可以用 sh.cat() 并删除临时文件。

实际上,这并不需要Python。仅Bash就足够了:

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

记住 shuf 无论如何,还是要在内存中读取整个文件。你必须有足够的内存来存储这个文件。