python,在创建对象时获取文件的名称
我不知道这是否不会重复,但我还没有找到任何东西,但是在这种情况下,很抱歉。
现在要我的问题。
我想制作简单的IDK如何将其称为基本脚本,这可以帮助我写入JSON文件更容易。
我拥有的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)
我的问题是如何做到这个,以便我可以在开始时创建一些对象,然后将文件添加到它,然后一次又一次地使用同一文件。我不必在函数的每个调用中提供文件名。
与此类似的东西:
import Tkinter
tk = Tkinter.tk()
或:
import logging
logger = logging.getLogger()
handler = logging.FileHandler(filename='test.log')
logger.addHandler(handler)
对不起,如果我写了此代码wring idk,这些模块的工作方式
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要两次打开,因为您只需使用“ R+”访问该文件,这也使您可以写入对文件的访问。 Seek方法将写作设置为文件的开头,因此您可以覆盖旧的JSON。
如果这不是理想的情况,则CSV文件可能更适合,因为您可以通过写入新行来继续添加数据,并且更容易处理较大的数据集。
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.
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.