0

I want to know how to write and read variables from a text file. So if I'm doing a game, for example, I'll be able to save the player's progress.

In pseudo code:

variable = 1
# write to text file that variable = 1
# close program
# open program
variable
# Then IDLE should output 1

If you can help me out I would really appreciate it!

6
  • Possible duplicate of importing text files with variables into python Commented Aug 22, 2018 at 15:45
  • You basically import the text file using json, imp, or simply as a .py file defined as a module (init file in folder), then to store, re-write the file. Commented Aug 22, 2018 at 15:46
  • If you don't mind, can you tell us that what have you tried? Commented Aug 22, 2018 at 15:47
  • If you need to store just dict, list, str, int, float, bool, None you can use the json module. If you need to store more complex types you can use the pickle module, with the caveat that "the pickle module is not secure against erroneous or maliciously constructed data," so you should "never unpickle data received from an untrusted or unauthenticated source." Commented Aug 22, 2018 at 15:50
  • 1
    Welcome to Stack Overflow! Please take the tour and read through the help center, in particular how to ask. Your best bet here is to do your research, search for related topics on SO, and give it a go. After doing more research and searching, post a Minimal, Complete, and Verifiable example of your attempt and say specifically where you're stuck, which can help you get better answers. Commented Aug 22, 2018 at 17:35

1 Answer 1

3

To write:

with open('game_vars.txt', 'w') as file:
    file.write(f'{score}\n{time}\n{high_score}\n')

To read:

with open('game_vars.txt', 'r') as file:
    score = int(file.readline().strip())
    time = int(file.readline().strip())
    high_score = int(file.readline().strip())
Sign up to request clarification or add additional context in comments.

Comments