Home > Software engineering >  python script shuffle file with lines
python script shuffle file with lines

Time:12-12

I have this script for years, I use it to scramble words in a text file. But I have a file line by line, and the script is shuffling but it deletes the line break he's leaving everything on the same line, do you have any solution for this? I tried 'sort -r' but it just does the reverse, it doesn't shuffle.

import random

file = open('myfile.txt', 'r')
text = file.read()
file.close()

text = text.split()
random.shuffle(text)
text = ' '.join(text)

print(text)

CodePudding user response:

If i understand correctly this should solve your issue:

import random

final_text = ""

with open("myfile.txt", "r") as file:
    lines = file.readlines()
    for i in range(len(lines)):
        lines[i] = lines[i].replace("\n", "")
    random.shuffle(lines)
    final_text = "\n".join(lines)

print(final_text)

CodePudding user response:

You can also use read().splitlines() to add all lines as element in list without trailing newline and print unpacked list using starred expression with \n as separator:

from random import shuffle

with open('myfile.txt') as file: text = file.read().splitlines(); shuffle(text)

print(*text, sep='\n')
  • Related