Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly mix the order of lines in a file

Tags:

python

Suppose I have a file containing some lines:

line 1 ...
line 2 ...
...
line n ...

Is it possible to have another file where the order of the lines will be randomly mixed ?

like image 239
shn Avatar asked Jan 25 '26 20:01

shn


2 Answers

The random module is your friend:

import random
with open("infile.txt") as f:
    lines = f.readlines()
random.shuffle(lines)
with open("outfile.txt", "w") as f:
    f.writelines(lines)

should do.

like image 147
Tim Pietzcker Avatar answered Jan 28 '26 10:01

Tim Pietzcker


1) read the file 2) store each line in a string array 3) shuffle string array 4) write file

I think that is what you're asking for?

like image 37
Eric Avatar answered Jan 28 '26 08:01

Eric