python初學之生成文件夾

由於工作需要每月月底需要根據實際情況建立文件夾,用python寫了個腳本生成文件夾及子文件夾。初學python,沒搞過開發,寫得不好勿噴!

 需求:從mkdir.txt裏面讀出行作爲文件夾名字,倒數三個作爲子文件夾名字。

wKioL1ZyxiCRhV05AAAoqkMCiCA739.png

#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 <module>
    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'


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章