1

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)
  • 2
    Hint: what does `text = ' '.join(text)` do? Could you replace `' '` with something else? Or maybe print your text a different way, without using `str.join()` at all? – ChrisGPT was on strike Dec 11 '22 at 20:32

2 Answers2

2

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)
Teddy
  • 452
  • 1
  • 12
0

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')
Arifa Chan
  • 947
  • 2
  • 6
  • 23