小编典典

随机混合300万行文件的行

python

一切都在标题中。我想知道是否有人知道一种快速且具有合理内存需求的方法来随机混合300万行文件的所有行。我想用简单的vim命令是不可能的,所以任何使用Python的简单脚本都不可能。我通过使用随机数生成器尝试使用python,但没有找到简单的出路。


阅读 155

收藏
2021-01-20

共1个答案

小编典典

import random
with open('the_file','r') as source:
    data = [ (random.random(), line) for line in source ]
data.sort()
with open('another_file','w') as target:
    for _, line in data:
        target.write( line )

那应该做。除非行数巨大(超过512个字符),否则300万行将适合大多数机器的内存。

2021-01-20