由于工作需要每月月底需要根据实际情况建立文件夹,用python写了个脚本生成文件夹及子文件夹。初学python,没搞过开发,写得不好勿喷!
需求:从mkdir.txt里面读出行作为文件夹名字,倒数三个作为子文件夹名字。
#coding:utf-8
import os
import sys
URL = r'D:\python case'
def nsfile(month):
if os.path.exists(URL):
print "目录文件dir已经存在!"
else:
os.mkdir(URL)
name = open(r'D:\python case\mkdir.txt')
line = name.readlines()
for i in range(0,len(line)-3):
dirname1 = os.path.join(URL,month+line[i].strip('\n'))#生成拼接路径,strip去除readlines()读出的换行符
os.mkdir(dirname1)
print dirname1
dirname2 = os.path.join(URL,month+line[i].strip('\n'),line[-3].strip('\n'))
os.mkdir(dirname2)
print dirname2
dirname3 = os.path.join(URL,month+line[i].strip('\n'),line[-2].strip('\n'))
os.mkdir(dirname3)
print dirname3
dirname4 = os.path.join(URL,month+line[i].strip('\n'),line[-1].strip('\n'))
os.mkdir(dirname4)
print dirname4
i = i+1
name.close()
if __name__ == '__main__':
month = raw_input("请输入月份(例如:12月上):")
nsfile(month)>>> ================================ RESTART ================================
>>>
请输入月份(例如:12月上):12月
目录文件dir已经存在!
D:\python case\12月文件夹1
D:\python case\12月文件夹1\文件夹00
D:\python case\12月文件夹1\文件夹01
D:\python case\12月文件夹1\文件夹02
D:\python case\12月文件夹2
D:\python case\12月文件夹2\文件夹00
D:\python case\12月文件夹2\文件夹01
D:\python case\12月文件夹2\文件夹02
D:\python case\12月文件夹3
D:\python case\12月文件夹3\文件夹00
D:\python case\12月文件夹3\文件夹01
D:\python case\12月文件夹3\文件夹02
D:\python case\12月文件夹4
D:\python case\12月文件夹4\文件夹00
D:\python case\12月文件夹4\文件夹01
D:\python case\12月文件夹4\文件夹02
D:\python case\12月文件夹5
D:\python case\12月文件夹5\文件夹00
D:\python case\12月文件夹5\文件夹01
D:\python case\12月文件夹5\文件夹02
D:\python case\12月文件夹6
D:\python case\12月文件夹6\文件夹00
D:\python case\12月文件夹6\文件夹01
D:\python case\12月文件夹6\文件夹02
D:\python case\12月文件夹7
D:\python case\12月文件夹7\文件夹00
D:\python case\12月文件夹7\文件夹01
D:\python case\12月文件夹7\文件夹02
中间没有去除readlines()读行时的换行符,会报错:Traceback (most recent call last):
File "D:\python case\mkdir.py", line 39, in
nsfile(month)
File "D:\python case\mkdir.py", line 28, in nsfile
os.mkdir(dirname3)
WindowsError: [Error 123] : 'D:\\python case\\12\xd6\xdc\xb1\xa8\xcf\xea\xc7\xe9\xce\xc4\xbc\xfe-DNS\xa1\xa2radius\n\\\xba\xcf\xb9\xe6\xa1\xa2\xc8\xf5\xbf\xda\xc1\xee'