Question

I have a program that imports a .py file that contains lists and dictionaries and uses them in the program. I am making another program that's purpose is to change the lists and dictionaries in this database .py file (either adding or removing parts of the lists/dictionaries). How would I go about doing this? Do i need to read in the .py file line by line, modify the lists, and overwrite the document? Is there a better way?

Any ideas would be much appreciated. If overwriting the file is the best plan, how do you do that?

Was it helpful?

Solution

Instead of directly editing py files within other py files, you should use the Pickle module. Pickle module allows you to save objects (dictionaries, lists, etc.) in a file which is binary formatted. Then you can fetch those dictionaries or whatever you saved, from the file itself without anything else.

You can also use the JSON module if you want pure simplicity and data interchange.

Here's how you can do something similar with the JSON module:

>> import json
>> a = {'foo': 'bar', 'hello': 'jello'}
>> json.dumps(a)
>> '{"foo": "bar", "hello": "jello"}'

NOTE: The json module will turn any single quote into double quotes as JSON itself does not accept single quote. And also notice the 's' after 'dump'. It makes sure that the function returns pure string rather than any binary format.

Hope, that helps you :D

OTHER TIPS

You can use SQLite or Pickle module instead, to allow easier data retrieval/manipulation from multiple programs/scripts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top