【问题标题】:Creating and naming files with a while function使用 while 函数创建和命名文件
【发布时间】:2014-04-28 16:02:41
【问题描述】:

我正在尝试为一年中的每一天创建一个文件,我想我会为此使用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()

【问题讨论】:

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


    【解决方案1】:

    你不能连接字符串和整数:

    name = date + '.txt' # TypeError
    

    但您可以使用str.format 创建文件名:

    name = "{0}.txt".format(date)
    

    使用str.format 还允许您强制四位数字,包括前导零:

    >>> "{0:04d}.txt".format(101)
    '0101.txt'
    

    (有关格式化选项的更多信息,请参阅 the documentation)。

    最后,鉴于您知道循环多少次,我建议在此处使用 rangefor 循环,以避免手动初始化和递增 date

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

    【讨论】:

    • 哇,真快。把它和你说的一样,现在效果很好。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2012-01-03
    相关资源
    最近更新 更多