Warm tip: This article is reproduced from stackoverflow.com, please click
create-directory matplotlib python

Create new existent folder with an identifier like folder_1, folder_2 etc.. with python

发布于 2020-03-27 10:15:38

I'm creating a new component for my code that can create copies of a folder with an identifier.

For example, I have a serial number and I'm creating a new folder for every serial number, inside every folder exist a new one named with the date that has been created the folder (in every folder i save some PDF's with the serial number with another script). This is the code that I'm using


import os
import matplotlib.pyplot as plt
import datetime
now = datetime.datetime.now()
date = now.strftime("%Y-%m-%d")


from pathlib import Path

def SN_folder(SN, SNs_path):


    if not os.path.exists(f"{SNs_path}/{SN}/{date}/Analysis1"):

        os.makedirs(f"{SNs_path}/{SN}/{date}/Analysis1")
        Analysis1_File_path = SNs_path + '/' + SN +'/' + 'Analysis1'

    if not os.path.exists(f"{SNs_path}/{SN}/{date}/Analysis2"):

        os.makedirs(f"{SNs_path}/{SN}/{date}/Analysis2")
        PHI_File_path = SNs_path + '/' + SN +'/'+ date +'/' + 'Analysis2'

    if not os.path.exists(f"{SNs_path}/{SN}/{date}/Analysis3"):

        os.makedirs(f"{SNs_path}/{SN}/{date}/Analysis3")

        PHII_File_path = SNs_path + '/' + SN +'/'+date+'/' + 'Analysis3'


SN_folder('752-0922', 'SNspath')

With this code i'm creating a folder for the Serial Number I'm giving, and inside another folder with the actual date, but if i run my code again with the same Serial Number it overwrites the data saved in this folder, i want to create a new folder with the same serial number and an identifier for the second run like : SN_2 or so.

Questioner
Rubicelia Patlán
Viewed
168
Grzegorz Bokota 2019-07-03 21:14

I do not fully understand the problem. but in line if not os.path.exists(f"{engines_path}/{SN}/{date}/Analysis1") you should change engines_path on SNs_path and most probably response is

import os
import matplotlib.pyplot as plt
import datetime
now = datetime.datetime.now()
date = now.strftime("%Y-%m-%d")


from pathlib import Path

def SN_folder(SN, SNs_path):

    SN_base = SN
    i = 1
    while os.path.exists(f"{SNs_path}/{SN}"):
        SN = SN_base + "_" + int(i)
        i += 1 

    if not os.path.exists(f"{SNs_path}/{SN}/{date}/Analysis1"):

        os.makedirs(f"{SNs_path}/{SN}/{date}/Analysis1")
        Analysis1_File_path = SNs_path + '/' + SN +'/' + 'Analysis1'

    if not os.path.exists(f"{SNs_path}/{SN}/{date}/Analysis2"):

        os.makedirs(f"{SNs_path}/{SN}/{date}/Analysis2")
        PHI_File_path = SNs_path + '/' + SN +'/'+ date +'/' + 'Analysis2'

    if not os.path.exists(f"{SNs_path}/{SN}/{date}/Analysis3"):

        os.makedirs(f"{SNs_path}/{SN}/{date}/Analysis3")

        PHII_File_path = SNs_path + '/' + SN +'/'+date+'/' + 'Analysis3'


SN_folder('752-0922', 'SNspath')