在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')

这是我创建一个具有可变文件名的新文件的代码。当我只使用filename="hello"时,它可以工作并创建hello.csv,但对于filename = "Attendance - " + todayDate,它显示以下错误:

Traceback (most recent call last):
File "e:CollegeCodingSYface-recogfile-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'

todayDate中的斜杠被python解释为路径。

你可能可以逃离它们,或者更简单的方法可能是将它们改为破折号:

todayDate = time_today.strftime('%d-%m-%Y')

这应该可以解决问题:

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

相关内容

  • 没有找到相关文章

最新更新