0

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)
2
  • are your tags and date in filepath really supposed to be in round brackets? Commented Jul 10, 2022 at 6:13
  • I think his idea is to print values of that variables.. Commented Jul 10, 2022 at 6:15

1 Answer 1

1

I see 2 issues in your logic.

  1. Never use predefine functions/variables as user define variable. Instead of Date rename your variable to file_date.
  2. 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))
Sign up to request clarification or add additional context in comments.

1 Comment

thank you, your solution works perfectly. I wasn't aware that "format" can be used for folders too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.