Python: how to store a variable
yg_be Posted messages 23437 Registration date Status Contributor Last intervention -
I currently have a small problem with a Python script: I need to save a variable so that even after closing the executable, the variable remains in memory.
A small example to illustrate:
-I open my file that asks for my age;
-I answer that I am x or y years old;
-I close the window;
-when I reopen it, I am told my age.
I don't know how to do this at all; I've done some research on the web, but I haven't found anything satisfactory, and everything that seemed suitable, I didn't understand.
Thank you in advance for your help,
Have a nice day!
Best regards,
Configuration: Windows / Edge 98.0.1108.43
16 answers
file = open("unfichier.txt", "w") file.write("LeTexte") file.close() --
Chouba, Moderator / My job is so secret that I don't even know what I do.
It depends on how long it needs to be remembered.
A simple solution is to write it in a file.
Should we create a shared online storage space?
If you put "a" instead, "append", it will write at the end.
Alright, thank you.
I am considering these two possibilities:
1) saving the text file on a website, and when the program starts, it fetches it and copies it to the computer. This could be a website of one of yours (sometimes this is included in internet subscriptions, or is available for free), or a file hosting service.
This might make your Python program more complex, and it may not work correctly on everyone's computers.
2) Using a service like Google Drive or One Drive, which will synchronize a file across different computers.
Small question, I wrote this piece of code, but I don't understand why it doesn't work...
Can you enlighten me?
os.system("cls")
print("\t\t\tTeacher area:\n")
print("You are going to change your password.")
sleep(2)
os.system("cls")
print("\t\t\tTeacher area:\n")
change_mot_de_passe1 = str(input("Enter your new password:\n"))
os.system("cls")
print("\t\t\tTeacher area:\n")
change_mot_de_passe2 = str(input("Confirm your new password:\n"))
if change_mot_de_passe1 == change_mot_de_passe2 :
print(change_mot_de_passe1)
mdp=str(change_mot_de_passe1)
f=open("age.dat",'w')
f.write(str(mdp))
f.close()
os.system("cls")
print("Your password has been successfully changed.")
sleep(2)
else :
os.system("cls")
print("\t\t\tTeacher area:\n")
print("Ouch... The two passwords are different.")
sleep(2)
os.system("cls")
choix_enseignant1 = True
os.system("cls")
When the change occurs, I find my file age.dat empty... I must have missed a step
Thank you in advance!
????
https://codes-sources.commentcamarche.net/faq/11288-les-balises-de-code
Also, be careful not to mix multiple topics in a discussion: it is sometimes preferable to create a new discussion.