-2

SO I'm making a calculator that turns any number into a specified number. The way that I want to specify this by having something like

numbertoturninto=*anynumber*

in a .txt file at the location

c:/python/calc2#/config.txt.

How do I do this? If you don't understand I will help.

Example: I have a .txt file. In that file, I have the number 4. I want var3 to be this number in a python program. (Hope this helps)

  • You mean how do you save text to a file in python? See https://stackoverflow.com/questions/5214578/python-print-string-to-text-file – Hektor Jan 27 '18 at 13:19
  • You are asking how to read your number to a python variable from a file? How about storing them in .json format? – Anton vBR Jan 27 '18 at 13:24
  • Oh, and the variable that I want to set dependent on the file is `var3`. – Robotech Gamer Jan 27 '18 at 13:25
  • 2
    Yes, I do not understand. Please give a specific example, using a specific number, explaining the specific context, and showing the specific desired result. See [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). NOTE: Your edit is not clear or specific enough. What exactly is `var3`? Is that line in the file the entire content of the file or just part of the content? And so on. – Rory Daulton Jan 27 '18 at 13:25
  • How do I store them in .json format? + Anton vBR – Robotech Gamer Jan 27 '18 at 13:26
  • 1
    @RobotechGamer You are asking for something quite simple. Try googling load file python, I might be able to give you an example or two – Anton vBR Jan 27 '18 at 13:36

1 Answers1

1

You are basically just asking how to store a variable in a text file. There are many ways to do this but I'd say JSON-files are pretty much made for this.

Using JSON

import json

# Create the file
with open('config.json', 'w') as f:
    json.dump({"var3":4}, f, indent = 2)

# The file now looks like this:
# {
#   "var3": 4
# }

# Read the file
with open('config.json') as f:
    config = json.load(f)

print(config['var3']) # prints 4

If you want to learn more. Try searching for dictionaries Python and JSON python.

Anton vBR
  • 18,287
  • 5
  • 40
  • 46