[英]Error in creating a file with variable name in python
from datetime import datetime
time_today = datetime.now()
todayDate = time_today.strftime('%d/%m/%Y')
filename = "Attendance - " + todayDate
with open(f'{filename}.csv', 'w') as fp:
fp.writelines(f'Name,Date,Time')
This is my code for creating a new file with a variable file name.这是我创建一个具有可变文件名的新文件的代码。 When i use just
filename="hello"
, it works and creates hello.csv but for filename = "Attendance - " + todayDate
it shows this error:当我只使用
filename="hello"
时,它会工作并创建hello.csv但对于filename = "Attendance - " + todayDate
它显示此错误:
Traceback (most recent call last):
File "e:\College\Coding\SY\face-recog\file-create.py", line 6, in <module>
with open(f'{filename}.csv', 'w') as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'Attendance - 29/03/2022.csv'
This should fix the problem:这应该可以解决问题:
from datetime import datetime
time_today = datetime.now()
todayDate = time_today.strftime('%d/%m/%Y')
filename = "Attendance - " + str(todayDate)
with open(f'{filename}.csv', 'w') as fp:
fp.writelines(f'Name,Date,Time')
The slashes in todayDate
are getting interpreted by python as a path. todayDate
中的斜杠被 python 解释为路径。
You can probably escape them or the easier method would probably be to change them to dashes instead:您可能可以转义它们,或者更简单的方法可能是将它们更改为破折号:
todayDate = time_today.strftime('%d-%m-%Y')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.