My Python Level: Beginner
MY QUESTION: If I wanted to make a random word generator that could show me all of the generated words previously produced (in a separate CSV file, for example), how would I do that?
This seems like it should be fairly simple, but I don't know what to look up to solve this problem. My thoughts were to use a loop somehow, keep reassigning values, or just copy/paste the newly generated words into another document every time I click Run.
An example:
Randomly Generated Words
Run #1 Output: ['dog', 'cat', 'bag']
Run #2 Output: ['tree', 'hug', 'food']
. . .
Run #10 Output: ['hamburger', 'tree', 'desk']
This updated CSV file would include ALL words that were randomly generated from the previous times the program was run and look something like this:
['dog', 'cat', 'bag', 'tree', 'hug', 'food', ..., 'word_x', 'word_x', 'word_x', ..., 'hamburger', 'tree', 'desk']
(I added 'tree' again to show that repetition is okay for this project)
This is what I have so far:
Note: This is a reduced version of the data I'm actually using
word_list = ['dog', 'cat', 'tree', 'hungry', 'food', 'hamburger', 'desk', 'bag', 'rain', 'car']
rand_word_rep = random.choices(word_list, k=3)
print(rand_word_rep)
Output
['dog', 'desk', 'car']
MY QUESTION (Again): If I wanted to make a random word generator that could show me all of the generated words previously produced (in a separate CSV file, for example), how would I do that?
Hopefully, I was clear in this post. If not, please let me know of your confusion and I'll clarify. Thanks in advance!
CodePudding user response:
You can just write to the file normally.
def write(data, filename):
with open(filename, 'a') as f:
f.write('\n'.join(data) '\n')
def read(filename):
with open(filename) as f:
return f.read().splitlines()
def clear(filename):
with open(filename, 'w'):
pass
word_list = ['dog', 'cat', 'tree', 'hungry', 'food', 'hamburger', 'desk', 'bag', 'rain', 'car']
rand_word_rep = random.choices(word_list, k=3)
write(rand_word_rep, 'chosen_words.txt')
After ['dog', 'cat', 'bag']
, the file would look like:
dog
cat
bag
After ['tree', 'hug', 'food']
, the file would look like:
dog
cat
bag
tree
hug
food
etc.
CodePudding user response:
You can write lines into a file like this:
with open('data.txt', 'at') as f:
f.write('this\n')
The 'a'
means 'append' and the 't'
means 'text'. Note that you are responsible for writing the lines to the file with the newline character.
Now you can read this file into a list:
with open('data.txt', 'rt') as f:
data = f.readlines()
Note that the file mode changed to 'rt'
for 'read text'.
The newlines are in there too; you can strip them off with str.strip()
, for example.