我正在尝试创建文件,一个文件代表一年中的每一天,我想为此使用 while
或 for
。但它似乎不起作用,因为我混合了数字和字母。
def CreateFile():
date = 101
#this is supposed to be 0101 (first of januar, but since i can't start with a 0 this had to be the other option)
while date <= 131:
name = (date)+'.txt'
date += 1
CreateFile()
最佳答案
您不能连接字符串和整数:
name = date + '.txt' # TypeError
但你可以使用str.format
创建文件名:
name = "{0}.txt".format(date)
使用 str.format
还允许您强制使用四位数字,包括前导零:
>>> "{0:04d}.txt".format(101)
'0101.txt'
(有关格式选项的更多信息,请参阅 the documentation)。
最后,鉴于您知道要循环多少次,我建议使用 range
的 for
循环。在这里,为了避免手动初始化和递增日期
:
for date in range(101, 132):
name = "{0:04d}.txt".format(date)
...
关于python - 使用 while 函数创建和命名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23345826/