Anthony Potter
Anthony Potter

Reputation: 33

Make new directory automatically in Python

Hi can someone help me to create a right path for my files in python? My path must be exported/files/{t}/{y}/filename. If i put in dir variable {y} on the end it won't work for some reason. My code is

tables=["table1","table2"]
years=["2010","2020"]
months=[1,2,3,4...12]
for t in tables:
     for y in years:
           for m in months:
                dir=(f"exported/files/{t}")
                os.mkdir(dir)
                sqlcode="select * from {t} where some condition..."
                filename= (f"{t}_{y}_{m}.sql")
                with open(os.path.join(dir,filename_),"w") as writer:
                     writer.write(sqlcode)

Upvotes: 0

Views: 64

Answers (2)

kzlca
kzlca

Reputation: 441

you should use os.makedirs() method instead of os.mkdir() method beacuse mkdir() can create a single sub-directory but makedirs() used to create branches also put exist_ok=True in os.makedirs() method and remove underscore from filename_ in line 11

should look like this:

tables=["table1","table2"]
years=["2010","2020"]
months=[1,2,3,4,5,6,7,8,9,10,11,12]
for t in tables:
     for y in years:
           for m in months:
                dir=(f"exported/files/{t}")
                os.makedirs(dir, exist_ok=True)
                sqlcode="select * from {t} where some condition..."
                filename= (f"{t}_{y}_{m}.sql")
                with open(os.path.join(dir,filename),"w") as writer:
                     writer.write(sqlcode)

Upvotes: 1

adir abargil
adir abargil

Reputation: 5745

you can use Path from pathlib :

from pathlib import Path



tables=["table1","table2"]
years=["2010","2020"]
months=[1,2,3,4...12]
for t in tables:
     for y in years:
           for m in months:
                full_path = f"exported/files/{t}"
                Path(full_path ).mkdir(parents=True, exist_ok=True)
                sqlcode="select * from {t} where some condition..."
                filename= (f"{t}_{y}_{m}.sql")
                with open(os.path.join(full_path ,filename),"w") as writer:
                     writer.write(sqlcode)     

Note: avoid using the keyword dir as it is saved keyword.

Upvotes: 1

Related Questions