How to Shuffle Text Lines in Python?

Estimated read time 2 min read

To shuffle text lines in Python, you can use the random module, which provides a way to generate random numbers and shuffle lists. Here’s an example of how to shuffle the lines of a text file in Python:

import random

# Read the text file
with open('filename.txt', 'r') as file:
    lines = file.readlines()

# Shuffle the lines
random.shuffle(lines)

# Write the shuffled lines to a new text file
with open('shuffled.txt', 'w') as file:
    file.writelines(lines)

In this example, the open() function is used to open the text file filename.txt in read mode, and the readlines() method is used to read all the lines of the file into a list lines. The random.shuffle() function is then used to shuffle the lines of the list in a random order. Finally, the open() function is used again to open a new text file shuffled.txt in write mode, and the writelines() method is used to write the shuffled lines of the list to the new file.

When you run this code, the program will read the lines of the text file filename.txt, shuffle them in a random order, and write the shuffled lines to a new text file shuffled.txt. Note that you can modify the file names and paths to read and write the text files from different locations. Also, note that this technique can be used to shuffle any list of strings in Python, not just text lines from a file.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply