我当前使用的代码是这样的:
date = time.strftime("%d/%m/%y")
filename = ('attendence{}' + str(date) +'.txt')
f = open(filename, 'w+')
但是,我收到的错误是这样的:
FileNotFoundError: [Errno 2] No such file or directory: 'attendence{}31/03/17.txt'
该错误与我的代码的其他部分无关,因为这可以工作。
f = open('attendence{}.txt', 'w+')
我的最终目标是创建一个包含当前日期的新文件。
最佳答案
问题出在日期格式上:
date = time.strftime("%d/%m/%y")
你可以尝试:
date = time.strftime("%d_%m_%y")
'attendence{}31/03/17.txt'
不仅仅是一个文件名,它还是一个相对路径:
- 1 个文件夹:
'出席{}31'
- 1 个子文件夹:
'03'
- 1 个文件名
'17.txt'
。
Python 提示文件夹'attendence{}31/03'
不存在。
请注意,{}
可能会使系统、某些程序或某些用户感到困惑。如果大括号内没有任何信息,您不妨将其删除。
关于python - 使用 python 中的变量创建新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43148154/