简体   繁体   English

如果文件名已存在于 python 中,则使用其他名称创建新文件

[英]Create new file with other name if file name already exist in python

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.但是,我想在我的代码中有一种方法可以直接注意到该文件是否已经存在,然后如果它存在,它会创建一个新文件,该文件不是 Y 而是 Y_2 或带有当前日期的 Y。 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

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 use os.path.exists(path_to_file) and putting it in a while loop would give you ability to check for existence of your file name and assign a new one (Y_2) if needed要检查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)

You just need to make a small change in your writeContentToFile function您只需要在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()

Explanation: 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 aa filename which is unique.说明:我们正在做的是,首先我们根据需要获取当前日期,然后我们创建一个新变量 new_endpoint 然后我们检查当前文件名是否存在,直到它存在我们将继续添加 _1、_2、 _3 ...到文件名,直到我们有一个唯一的文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM