【问题标题】:Trying to create files for each day in a month尝试为一个月中的每一天创建文件
【发布时间】:2014-05-02 11:26:04
【问题描述】:

我正在尝试为一年中的每一天创建一个文件,所以 1 月 31 日,2 月 28 日等等,但由于这是一项学校作业,我也不能有太长的代码,所以这是一个聪明的方法这样做会很好。在他们那一刻我正在尝试这个(下),但它说我不能使用列表作为范围对象

def MonthList():

    lenghtOnMonthList = [32,29,32,31,32,31,32,32,31,32,31,32]

    return lenghtOnMonthList


def CreateFile(lenghtOnMonthList):

    for month in range(1,13):

        if month < 10:

            month = "0" + str(month)

        day = 1 

        for day in range(1,lenghtOnMonthList):

            if day < 10:

                day = "0" + str(day)

            file = open(str(month) + str(day)+'.txt', "a")

            day = int(day)

            day += 1

基本上我想将每个文件命名为 0101 为 1 月的第一个,0102 为第二个,一直到 1231 和 ocfourse 跳过 0229(因为我在 2 月使用 28 天)

但是为什么我不能用我的列表来显示第一个月是 32 天(因为它给出了 31 天)而第二个月是 29 天?

谢谢 //Kasper

【问题讨论】:

    标签: python list python-3.x range


    【解决方案1】:

    一个小代码可能会解决你的问题

    from calendar import monthrange
    import os
    for i in range(1,13):
        x=monthrange(2014,i)
        for j in range(1,x[1]+1):
            cmd="%02d%02d" % (i,j)
            os.system("touch " + str(cmd))
    

    touch 命令在基于 unix 的系统中用于创建文件。 如果你使用的是windows系统,那么你可以使用python的subprocess module。 如果您想使用子进程模块,请查看https://docs.python.org/2/library/subprocess.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 2022-01-01
      相关资源
      最近更新 更多