I have a loop that creates multiple folders/sub-folders and csv. I was able to create folder/sub-folders with {date} and (tag) using os.
However, when I try to use the created file path for the cvs generated from the loop, i get
Cannot save file into a non-existent directory: '/home/user/Desktop/test/(date)/(tag)
moi, m24or when i switch from (date)/(tag) to {date}/{tag}, i get
KeyError: 'date'
Both data and tag are variable which changes after each loop.
main_dir = f"/home/user/Desktop/test/{date}/"
os.makedirs(main_dir str(tag))
filepath = r'/home/user/Desktop/test/(date)/(tag)/{}.csv'
df.to_csv(filepath.format(filename), index = True, header=True)
CodePudding user response:
I see 2 issues in your logic.
- Never use predefine functions/variables as user define variable. Instead of Date rename your variable to file_date.
- When you use raw string and wanted to display variable value, you have to use "format"
Please find the solution below.
main_dir = f"/home/user/Desktop/test/{file_date}/"
os.makedirs(main_dir str(tag))
filepath = r'/home/user/Desktop/test/{}/{}/{}.csv'
print(filepath.format(file_date,tag,filename))