[英]How do I append further JSON to the end of another JSON file when the scripts are in cgi-bin?
我真的是Python的新手,我正在嘗試創建一個將JSON附加到現有JSON文件末尾的腳本。 我的服務器運行的方式是僅執行cgi-bin文件夾(public_html / cgi-bin)中的Python文件夾。
我在同一目錄中有JSON文件和Python腳本文件,並嘗試使用以下代碼對其進行更改:
#!/usr/bin/env python
import cgi
import json
new_data = {"2": {"title": "what", "date": "tomorrow"}}
print("Content-type: application/json\n\r")
with open("jobs.json") as file:
data = json.load(file)
data.update(new_data)
with open('jobs.json', 'w') as file:
json.dump(data, file)
但是,當我加載該頁面時,沒有任何反應, jobs.json
保持不變。
我與服務器提供商進行了交談,他們說cgi-bin中的JSON文件被認為只是在public_html中(如果我在地址欄中訪問JSON文件,它會很好,而cgi-bin目錄中卻沒有) )。 然后,如果顯然返回public_html,我如何訪問users.json
?
Python文件的路徑是/public_html/ooproject/two.py
而jobs.json
在同一目錄中。
您可以嘗試__file__
變量。 它包含腳本的名稱,並與os.path
結合使用,可能會提供所需的內容。 嘗試這個:
#!/usr/bin/env python
import cgi
import json
import os.path
new_data = {"2": {"title": "what", "date": "tomorrow"}}
print("Content-type: application/json\n\r")
script_dir = os.path.dirname(os.path.abspath(__file__))
fname = os.path.join(script_dir, 'jobs.json')
with open(fname) as f:
data = json.load(f)
data.update(new_data)
with open(fname, 'w') as f:
json.dump(data, f)
注意:避免使用file
作為變量名,因為它是Python類型的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.