如果文件名已存在于 python 中,则使用其他名称创建新文件
目前我的脚本可以创建一个文件和内容。但是,我希望在我的代码中有一种方法可以直接注意到该文件是否已经存在,然后如果存在,它会创建一个新文件,该文件不是 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
For the moment my script can create a file and the content. However, I would like to have a way in my code to directly noticed if the file already exists, and then if it exists, it creates a new file which will not be Y but Y_2 or Y with the current date. So I can have a history of my file created.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想我不太明白你的问题。但根据我所得到的,我可以帮助你这么多:
要检查
if是否存在
,您可以使用os.path.exists(path_to_file)
并将其放入while
循环中,这样您就可以检查您的文件名是否存在,并根据需要指定一个新文件名(Y_2)I don't think I understood your question well. but from what I got I can help you this much:
for checking
if exists
you can useos.path.exists(path_to_file)
and putting it in awhile
loop would give you ability to check for existence of your file name and assign a new one (Y_2) if needed您只需要在
writeContentToFile
函数中进行一些小的更改说明:
我们正在做的是,首先我们根据需要获取当前日期,然后创建一个新变量 new_endpoint,然后检查当前文件名是否存在,直到它存在为止,我们将继续添加 _1、_2 、_3。 .. 到文件名,直到我们有一个唯一的文件名。
You just need to make a small change in your
writeContentToFile
functionExplanation:
What we are doing is that first we are getting the current date as you need, then we are creating a new variable new_endpoint and then we are checking if the current filename exists and until it exists we will keep on adding _1, _2 ,_3... to the filename until we have a a filename which is unique.