Skip to content

Instantly share code, notes, and snippets.

@onlyforbopi
Created October 18, 2022 14:25
Show Gist options
  • Save onlyforbopi/70f20784d274b59f3bddab075940c95e to your computer and use it in GitHub Desktop.
Save onlyforbopi/70f20784d274b59f3bddab075940c95e to your computer and use it in GitHub Desktop.
class ShuffleLine:
def __init__(self, inp_file):
self.file_name = inp_file
# Shuffling with help of list of tuples
def shuffle_read(self):
file_name = self.file_name
with open(file_name, 'r') as f:
data = [(random.random(), line) for line in f]
data.sort()
with open(file_name, 'w') as target:
for _, line in data:
target.write(line)
return len(data)
# Shuffling via random.shuffle(method) and then writing the shuffled
# content to the same file
def shuffle_readline(self):
file_name = self.file_name
with open(file_name, 'r') as f:
lines = f.readlines()
random.shuffle(lines)
with open(file_name, 'w') as f:
f.writelines(lines)
return len(lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment