If you have any questions, comments or issues with this project please post them here!
My code isn’t working :
import random, os, time
while True:
print('🌟Idea Storage🌟\n')
print('Operations to be performed:\n1. Add an idea\n2. Load a random idea\n')
op = input('Choice > ')
if op == '1':
f = open('my.ideas', 'a+')
idea = input('Input an idea > ')
f.write(f'{idea}\n')
time.sleep(1)
print('Your idea has been stored')
f.close()
time.sleep(1)
os.system('clear')
continue
else:
f.open('my.ideas', 'a+')
r = f.read()
print(f)
re = f.read().split('\n')
f.close()
print(random.choice(re))
time.sleep(3)
continue
Hey, please don’t the same question in multiple places, this just adds clutter to the community space. If your original question doesn’t get answered for a while (close to a week), it would be appropriate to reply to your original post asking for help, which bumps it back to the top of the latest list. If you want to add additional information to your question, you can edit it or add a reply containing this information.
Hi @SUMAYDOHARE thanks for your question. Can you elaborate on this please? What error messages do you see?
If you could also share a link to your Repl it would allow others in the community to take a look at the code, run it, and then offer some ideas.
import random, os, time
while True:
print('🌟Idea Storage🌟\n')
print('Operations to be performed:\n1. Add an idea\n2. Load a random idea\n')
op = input('Choice > ')
if op == '1':
f = open('my.ideas', 'a+')
idea = input('Input an idea > ')
f.write(f'{idea}\n')
time.sleep(1)
print('Your idea has been stored')
f.close()
time.sleep(1)
os.system('clear')
continue
else:
if (not os.path.exists("my.ideas")):
print("you have to add ideas first!")
continue
f = open('my.ideas')
re = f.read().strip().split('\n')
f.close()
print(random.choice(re))
time.sleep(3)
continue
Can someone explain to me why I need to
f.close()
the file again, after reading out the contents?
to me this feels like like only being able to paste something you have copied from a file after you close the file. A bit strange.
Thanks for the explanation!
The continue before the else is useless.
As for your question. You do not need to open and close all the time, you can also open and close only when you are finished.
To do that you need to add a thirds option to add and read. A stop option.
With that you can open the file before the wile loop and close it once … but then i would advice to Google the with structure for using files. Much cleaner .
Thanks for your help