使用python中的变量创建新文件

时间:2017-03-31 19:18:37

标签: python file variables makefile

我目前使用的代码是:

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

我的最终目标是创建一个包含当前日期的新文件。

1 个答案:

答案 0 :(得分:1)

问题在于日期格式:

date = time.strftime("%d/%m/%y")

你可以尝试:

date = time.strftime("%d_%m_%y")

'attendence{}31/03/17.txt'不仅仅是一个文件名,它是一个相对路径:

  • 1个文件夹:'attendence{}31'
  • 1子文件夹:'03'
  • 1个文件名'17.txt'

Python抱怨文件夹'attendence{}31/03'不存在。

请注意,{}可能会混淆系统,某些程序或某些用户。如果大括号内没有信息,你也可以删除它们。