pythonrandomshuffle

python random.shuffle from lists in a text file


Trying to do a random.shuffle which works well if the list is declared. In example 2, I'm trying to do this from a file that has 1000 entries with the first two lines shown. Is the txt file formatted wrong? I cant get this to work. I've tried many examples found on the net.

import random

#example 1

list1 = ['sub', 'gig', 'bug']

random.shuffle(list1)

print('list1:', list1)

#Results

list1: ['bug', 'gig', 'sub']

#example 2 #masterwords.txt has this on line 1 and 2

['bug', 'gig', 'sub']

['frog', 'dog', 'cat']

with open("masterwords.txt", mode="r", encoding="utf-8") as file:

lines = []

   for line in file:

      line = line.strip()

      lines.append(line)

      random.shuffle(lines)

print(lines)

#Results:

["['frog', 'dog', 'cat']", "['bug', 'gig', 'sub']", '']

Solution

  • The data in the file are string representations of Python lists. You need to convert them into runtime lists. You can do this with the ast.literal_eval() function.

    Let's assume the input file contains:

    ['bug', 'gig', 'sub']
    ['frog', 'dog', 'cat']
    

    Then:

    from ast import literal_eval
    from random import shuffle
    
    with open("masterwords.txt") as mw:
        for line in mw:
            lst = literal_eval(line)
            shuffle(lst)
            print(lst)
    

    Possible output:

    ['sub', 'gig', 'bug']
    ['cat', 'dog', 'frog']