I just started programming in Python so I would love a detailed explanation. Let's say I have a list of words at file number 1:
list=["leaf","cream","pickles","vinegar","gouda","almond","fire","orbit","spider","symbol"]
In a cache called "Random Words".
Now I'm coding a different file (file 2) called "The Selected Word". I want to import a different word from file 1 each time I run file 2. What command should I write? I tried this:
word = random.choice.open("random words","w")
print(word)
And it didn't work ...
to make things simple make sure randomwords.py and theselectedword.py are in the same folder and directory. in randomwords.py
list_of_words = ['age','body',.... etc]
#do not use 'list' to name a variable or object,so as not to override the list function called list()
then in theselectedword.py
from randomwords import list_of_words
import random
word = random.choice(list_of_words)
print(word)
You could use Pythons module system for this task:
Save list in python script, "Random_Words.py":
my_list = ["leaf"
, "cream"
, "pickles"
, "vinegar"
, "gouda"
, "almond"
, "fire"
, "orbit"
, "spider"
, "symbol"
]
And now import this script as a module in the other program, "The_Selected_Word.py":
from Random_Words import my_list
word = random.choice(my_list)
print(word)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With