python script shuffle file with lines

Question:

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)
Asked By: David Kennedy

||

Answers:

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)
Answered By: Teddy

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')
Answered By: Arifa Chan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.