use*_*082 2 python list range python-3.x
我正在尝试为一年中的每一天创建一个文件,因此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
Run Code Online (Sandbox Code Playgroud)
基本上我想命名每个文件0101为1月的第一个,0102为第二个,一直到1231和ocfourse跳过0229(因为我在2月使用28天)
但为什么我不能用我的清单来表明第一个月做32天(因为它给31)而第二个月做29天?
谢谢你!Kasper
一个可以解决问题的小代码
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))
Run Code Online (Sandbox Code Playgroud)
touch命令用于基于unix的系统来创建文件.如果您使用的是Windows系统,则可以使用python的子进程模块.如果要使用子进程模块,请查看https://docs.python.org/2/library/subprocess.html