Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use python readlines method in random order

Tags:

python

How can one use the readlines() method to read a file in a random shuffled manner i.e. random.shuffle()

file = open(filename)
data = file.readlines()           
file_length =  len(data)
like image 667
DevEx Avatar asked Jan 10 '23 18:01

DevEx


2 Answers

Get them into a list with lines = file.readlines(), and then random.shuffle(lines) that list (import random module).

like image 152
alex Avatar answered Jan 18 '23 22:01

alex


You can store the entire file as a list of lines with:

f = open(filename)
data = f.read() # the whole file in one string
lines = data.split('\n')

Then use random to access lines.

like image 23
kadu Avatar answered Jan 18 '23 22:01

kadu