简体   繁体   中英

File or directory doesn't exist

I'm trying to use the current date as the file's name, but it seems either this can't be done or I'm doing something wrong. I used a variable as a name for a file before, but this doesn't seem to work.

This is what I tried:

import time

d = time.strftime("%d/%m/%Y")

with open(d +".txt", "a+") as f:

    f.write("")

This is just to see if it create the file. As you can see I tried with a+ because I read that creates the file if it doesn't exist and I still get the same error.

The problem is with how you're using the date:

d = time.strftime("%d/%m/%Y")

You can't have a / in a filename, because that's a directory instead. You haven't made the directory yet. Try using hyphens instead:

d = time.strftime("%d-%m-%Y")

You almost certainly don't want to make directories in the structure day/month/year , so I assume that's not what you were intending.

You are including directory separators ( / ) in your filename, and those directories are not created for you when you try to open a file. There is either no 26/ directory or no 26/02/ directory in your current working path.

You'll either have to create those directories by other means, or if you didn't mean for the day and month to be directories, change your slashes to a different separator character:

d = time.strftime("%d-%m-%Y")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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