简体   繁体   English

文件或目录不存在

[英]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. 如您所见,我尝试使用a+因为我读过它会创建一个不存在的文件,并且仍然会出现相同的错误。

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. 几乎可以肯定,您不想在day / month / year结构中创建目录,因此我认为这不是您想要的。

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. 当前的工作路径中没有26/目录,也没有26/02/目录。

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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