简体   繁体   中英

How to update data in python file, from another?

I'm trying to create simple 'accounter', which can show your cash balance and logs of operations. Operations are simple: receive(amount, subject) and spend(amount, subject). They change balance and write the changes into logs with a timestamp. Should've.

I'm trying to use another.py file as a database. Although I can import, read and use database, I can't seem to find a way to write changes into it. Couldn't find any solution that I need anywhere. There are some ways like using json, and other. But I am trying to use exactly py file.

Here's db.py:

balance = 0

balance_logs = [
    ['305', 'spent','5','coke','2020-08-18 20:00'],
    ['202', 'spent','3','icecream','2020-08-18 20:00']
]

So, I need to change balance value and append a list into balance_logs . Also I may add more data into db.py, so it will be good if I won't need to <copy file contents fully -> modify the parts you need -> dump into file, by fully recreating it> method.

If I understand what I mean, saving this file in json format I believe would be ok. There are tutorials about this online, however I will try to summarise the basics here. To open and correctly load data from json, you can use:

import json 
with open('example.txt') as json_file:
    data = json.load(json_file)

To save data to a file, you can use:

import json
with open('example.txt', 'w') as json_file:
    json.dump(data, json_file)

To append data with json, you can use a mix of these two, for example taking a part of the dictionary stored in the json, operating on it and then saving it again. An example is:

import json 
with open('example.txt') as json_file:
    data = json.load(json_file)

# Do something to the data, for example...
data['foo'] = 'bar'

with open('example.txt', 'w') as json_file:
    json.dump(data, json_file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM