Medochikita
Medochikita

Reputation: 11

Python, getting name of a file at the creation of a object

i dont know if this wont be a duplicate but i havent found anything, but in that case sorry.
Now to my question.
I want to make simple idk how to call it basicly script that would help me write to json file more easy.
What i have rn:

import json

def addValue(pathToFile, index, value):
    with open(pathToFile, "r") as f:
        data = json.load(f)

    data[index] = value

    with open(pathToFile, "w") as f:
        json.dump(data, f, indent=4)

And my question is how could i make this so that i can create some object at the start and then add the file to it and then just use the object again and again with the same file. Something that i wouldnt have to provide the file name at every call of the function.
Something similar to this:

import Tkinter

tk = Tkinter.tk()

or:

import logging

logger = logging.getLogger()
handler = logging.FileHandler(filename='test.log')
logger.addHandler(handler)

sorry if i wrote this code wring idk really how these modules work

Upvotes: 0

Views: 261

Answers (1)

Charlie Ciampa
Charlie Ciampa

Reputation: 75

You don't need to write open twice as you can just access the file with "r+" which also gives you write access to the file. The seek method sets the writing to the beginning of the file so you can override the old json.

import json

def addValue(pathToFile, index, value):
    with open(pathToFile, "r+") as file:
        data = json.load(file)
        data[index] = value
        file.seek(0)
        json.dump(data, file, index=4)

If this is not ideal, a CSV file may be more suitable as you can continue to add data by just writing to a new line, and it is easier to deal with larger sets of data.

Upvotes: 1

Related Questions