2

Brand new to stack and python; hopefully someone wiser than myself can help. I have searched up and down and can't seem to find an actual answer to this, apologies if there is an exact answer and I've missed it :( (the few that I've found are either old or don't seem to work).

Closest I've found is Best way to retrieve variable values from a text file? Alas, imp seems to be depreciated and tried figuring out importlib but little above my current brain to figure out how to adapt it as errors throw up left and right on me. This is very close to what I want and could potentially work if someone can help update with new methods, alas still doesn't have how to overwrite the old variable.

= - - Scenario - - =

I would like to create a preferences file (let's call it settings.txt or settings.py: doesn't need to be cross-compatible with other languages, but some reason I'd prefer txt - any preference/standards coders can impart would be appreciated?).

\\\ settings.txt\
water_type = "Fresh"\
measurement = "Metric"\
colour = "Blue"\
location = "Bottom"\
...

I am creating a script main_menu.py which will read variables in settings.txt and write to this file if changes are 'saved'

ie. "select water type:"

  1. Fresh
  2. Salt

if water_type is the same as settings.txt, do nothing, if water_type different, overwrite the variable in the settings.txt file

Other scripts down the line will also read and write to this settings file.

I've seen:

from settings import *

Which seems to work for reading the file if I go the settings.py path but still leaves me on how do I overwrite this.

also open to any better/standard/ideas you guys can think of.

Appreciate any help on this!

Goldwave
  • 599
  • 3
  • 13
Dave
  • 33
  • 6

4 Answers4

4

Here are some suggestions that may help you:

  • Use a json file:

settings.json

{
  "water_type": "Fresh",
  "measurement": "Metric",
  "colour": "Blue",
  "location": "Bottom",
...
}

then in python:

import json

# Load data from the json file
with open("settings.json", "r") as f:
    x = json.load(f) # x is a python dictionary in this case

# Change water_type in x
x["water_type"] = "Salt"

# Save changes
with open("settings.json", "w") as f:
    json.dump(x, f, indent=4)
  • Use a yaml file: (edit: you will need to install pyyaml)

settings.yaml

water_type: Fresh
measurement: Metric
colour: Blue
location: Bottom
...

then in python:

import yaml

# Load data from the yaml file
with open("settings.yaml", "r") as f:
    x = yaml.load(f, Loader=yaml.FullLoader) # x is a python dictionary in this case

# Change water_type in x
x["water_type"] = "Salt"

# Save changes
with open("settings.yaml", "w") as f:
    yaml.dump(x, f)
  • Use a INI file:

settings.ini

[Preferences]
water_type=Fresh
measurement=Metric
colour=Blue
location=Bottom
...

then in python:

import configparser

# Load data from the ini file
config = configparser.ConfigParser()
config.read('settings.ini')

# Change water_type in config
config["Preferences"]["water_type"] = "Salt"

# Save changes
with open("settings.ini", "w") as f:
    config.write(f)
I. Al.
  • 166
  • 1
  • 6
1

For .py config files, it's usually static options or settings.

Ex.

# config.py
STRINGTOWRITE01 = "Hello, "
STRINGTOWRITE02 = "World!"
LINEENDING = "\n"

It would be hard to save changes made to the settings in such a format.

I'd recommend a JSON file.

Ex. settings.json

{
    "MainSettings": {
        "StringToWrite": "Hello, World!"
    }
}

To read the settings from this file into a Python Dictionary, you can use this bit of code.

import json # Import pythons JSON library
JSON_FILE = open('settings.json','r').read() # Open the file with read permissions, then read it.
JSON_DATA = json.loads(JSON_FILE) # load the raw text from the file into a json object or dictionary
print(JSON_DATA["MainSettings"]["StringToWrite"]) # Access the 'StringToWrite' variable, just as you would with a dictionary.

To write to the settings.json file you can use this bit of code

import json # import pythons json lib
JSON_FILE = open('settings.json','r').read() # Open the file with read permissions, then read it.
JSON_DATA = json.loads(JSON_FILE) # load the data into a json object or dictionary
print(JSON_DATA["MainSettings"]["StringToWrite"]) # Print out the StringToWrite "variable"
JSON_DATA["MainSettings"]["StringToWrite"] = "Goodnight!" # Change the StringToWrite
JSON_DUMP = json.dumps(JSON_DATA) # Turn the json object or dictionary back into a regular string
JSON_FILE = open('settings.json','w') # Reopen the file, this time with read and write permissions
JSON_FILE.write(JSON_DUMP) # Update our settings file, by overwriting our previous settings

Now, I've written this so that it is as easy as possible to understand what's going on. There are better ways to do this with Python Functions.

Goldwave
  • 599
  • 3
  • 13
  • Yeah I managed to get it working with these examples. What exactly is the difference between .dump and .write. I've been using dump and it seems to be working perfectly – Dave Oct 12 '20 at 18:46
  • You may be able to use dump too, i'm not sure. – Goldwave Oct 14 '20 at 07:26
0

You guys are fast! I'm away from the computer for the weekend but had to log in just to say thanks. I'll look into these more next week when I'm back at it and have some time to give it the attention needed. A quick glance could be a bit of fun to implement and learn a bit more.

  • Had to answer as adding comment only is on one of your guys solutions and wanted to give a blanket thanks to all!

Cheers

Dave
  • 33
  • 6
-1

Here's a python library if you choose to do it this way. If not this is also a good resource.

Creating a preferences file example

Writing preferences to file from python file

import json 
  
# Data to be written 
dictionary ={ 
    "name" : "sathiyajith", 
    "rollno" : 56, 
    "cgpa" : 8.6, 
    "phonenumber" : "9976770500"
} 
  
# Serializing json  
json_object = json.dumps(dictionary, indent = 4) 
  
# Writing to sample.json 
with open("sample.json", "w") as outfile: 
    outfile.write(json_object) 

Reading preferences from .json file in Python

import json

# open and read file content 
with open('sample.json') as json_file:
    data = json.load(json_file)


# print json file
print(data)
Null
  • 119
  • 6
  • This got me started, so thanks. Managed to remove a lot of the extra as I don't need to write the entire file each time. The solutions proposed further up allow me to handle individuals! – Dave Oct 12 '20 at 18:47