目前我的腳本可以創建一個檔案和內容。但是,我想在我的代碼中直接注意到檔案是否已經存在,然后如果它存在,它會創建一個新檔案,該檔案不是 Y,而是 Y_2 或 Y 與當前日期。所以我可以創建我的檔案的歷史記錄。
customername = "X"
workspacename = "Y"
structureDict = {
"attribute": ["attributes/screens"],
"content": ["containers",
"dataProcessing",
"fields",
"properties",
"sources",
"structures",
"usages"],
"types": ["containers/types",
"dataProcessing/types",
"fields/types",
"properties/types",
"sources/types",
"structures/types",
"usages/types"]
}
for category in structureDict:
for endpoint in structureDict[category]:
print (category, endpoint)
def writeContentToFile(mode, customername, workspacename, category, endpoint, jsonContent):
path = os.path.join(os.getcwd(), customername, workspacename, category)
Path(path).mkdir(parents=True, exist_ok=True)
with open(path "/" endpoint '.json', mode, encoding='utf-8') as f:
json.dump(jsonContent, f, ensure_ascii=False, indent=4)
f.close()
for category in structureDict:
for endpoint in structureDict[category]:
endpointFilename = endpoint
if category in ["attribute", "types"]:
endpointFilename = endpoint.replace("/", "_")
url = url_X endpoint
params = {"versionId":Workspace_id,
"includeAccessData":"true",
"includeAttributes":"true",
"includeLinks":"true"
}
jsonResponse = requests.get(url, params=params, headers={"Authorization":accessToken}).json()
writeContentToFile('a', customername, workspacename, category, endpointFilename, jsonResponse)
try:
jsonResponsePages = jsonResponse['pages']
if int(jsonResponsePages) != 1:
for i in range(2, jsonResponsePages 1, 1):
params["page"] = str(i)
jsonResponse = requests.get(url=url, params = params, headers={"Authorization":accessToken}).json()['results']
writeContentToFile('a', customername, workspacename, category, endpointFilename, jsonResponse)
except:
print(endpoint)
next
uj5u.com熱心網友回復:
我認為我沒有很好地理解你的問題。但據我所知,我可以為您提供很多幫助:
為了檢查if exists您是否可以使用os.path.exists(path_to_file)并將其放入回圈中,您可以檢查您的檔案名是否存在,并在需要時while分配一個新檔案名(Y_2)
def writeContentToFile(mode, customername, workspacename, category, endpoint, jsonContent):
path = os.path.join(os.getcwd(), customername, workspacename, category)
Path(path).mkdir(parents=True, exist_ok=True)
c = 1
while os.path.exists(path "/" (endpoint if c == 1 else endpoint f'_{c}') '.json'): c = 1
with open(path "/" (endpoint if c == 1 else endpoint f'_{c}') '.json', mode, encoding='utf-8') as f:
json.dump(jsonContent, f, ensure_ascii=False, indent=4)
uj5u.com熱心網友回復:
你只需要對你的writeContentToFile功能做一個小的改變
import os
from datetime import datetime
def writeContentToFile(mode, customername, workspacename, category, endpoint, jsonContent):
path = os.path.join(os.getcwd(), customername, workspacename, category)
date = datetime. now(). strftime("%Y_%m_%d") #getting the current date
new_endpoint=endpoint[:] #Creating a new endpoint value
index=2 #setting the counter to 2
while os.path.exists(os.path.join(path, new_endpoint)): #keep on checking Y_DATE_2 , Y_DATE_3 until filename is unique
new_endpoint=endpoint '_' date '_' index
index =1
Path(path).mkdir(parents=True, exist_ok=True)
with open(path "/" new_endpoint '.json', mode, encoding='utf-8') as f:
json.dump(jsonContent, f, ensure_ascii=False, indent=4)
f.close()
說明:我們所做的是首先我們根據需要獲取當前日期,然后我們正在創建一個新變數 new_endpoint 然后我們正在檢查當前檔案名是否存在,直到它存在我們將繼續添加 _1, _2 , _3... 到檔案名,直到我們有一個唯一的檔案名。
uj5u.com熱心網友回復:
您可以嘗試在代碼中使用日志記錄。正如您可能已經知道的那樣,這是內置于 Python 中的。
匯入日志
將日志記錄級別設定為您需要的級別(10 = 除錯,20 = 資訊,30 = 警告,40 = 錯誤,50 = 嚴重)
對于你需要的東西,我推薦 20。
根據您希望它的深度,您還可以腌制您的檔案并添加一個 if 陳述句來檢查您收到的日志資訊是否與現有的腌制檔案匹配(人們不建議使用腌制,因為在 unpickle 方面的安全性操作)。
您可能還想打開您撰寫的檔案,指定它們不可附加。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/433023.html
標籤:Python json for循环 with-语句 写入文件
上一篇:用for回圈中的值填充陣列
