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

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

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

最佳答案

问题出在日期格式上:

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/

相关文章:

python - 使用django上传图片

python : Printing contents of a file to the terminal

Java 读/写文件

c - 在函数之间传递参数

python - 通过 Geodjango 中的几何交集关联两个模型

python - Pandas 按名称和最近日期合并

javascript - nodejs lstat 找不到文件

javascript - 动态 JavaScript 变量名称

php - 在 jQuery 函数中使用 smarty 变量

python - python类的所有语句在没有对象创建的情况下执行