[英]Python copy files to a new directory and rename if file name already exists
[英]Create new file with other name if file name already exist in 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
我不认为我理解你的问题。 但从我得到的信息来看,我可以帮助你这么多:
要检查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)
您只需要在writeContentToFile
function 中做一个小改动
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 ...到文件名,直到我们有一个唯一的文件名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.