-4

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']", ''] 
1
  • Take a look at the literal_eval function from the ast module Commented Oct 23, 2024 at 7:24

1 Answer 1

1

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'] 
Sign up to request clarification or add additional context in comments.

1 Comment

this worked perfectly. would it make a difference if i changed the masterwords.txt to masterwords.py and imported it then ran the code? Anyway, your solution was perfect, thank you!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.