python - 使用 while 函数创建和命名文件

标签 python for-loop python-3.x while-loop

我正在尝试创建文件,一个文件代表一年中的每一天,我想为此使用 whilefor 。但它似乎不起作用,因为我混合了数字和字母。

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

最后,鉴于您知道要循环多少次,我建议使用 rangefor 循环。在这里,为了避免手动初始化和递增日期:

for date in range(101, 132):
    name = "{0:04d}.txt".format(date)
    ...

关于python - 使用 while 函数创建和命名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23345826/

相关文章:

linux - Linux 终端中的 For 循环

python - 如何使用 iterrows 或 itertuples 有效地迭代以从旧数据帧创建新数据帧

python - 如何选择 pandas 中一组的最后一行?

python - 如何用python实现构建变体?

python - 使用 python pyodbc 和 pandas 数据框将数据从 SQL Server 导出到 Excel

python - 谷歌波 OnBlipSubscribed

c - 不执行 for 循环的最后一行并且完成后不退出 - C

python - 打开文本文件

python - 打印行的最短代码以 ['a' , 'b' ] 和以 ['y' , 'z' ] 结束 Python 3

android - 使用 Python/(GAE) 为 Android 应用推送通知的服务器端实现