233饿13 发表于 2015-12-18 08:33:27

python初学之生成文件夹

由于工作需要每月月底需要根据实际情况建立文件夹,用python写了个脚本生成文件夹及子文件夹。初学python,没搞过开发,写得不好勿喷!

需求:从mkdir.txt里面读出行作为文件夹名字,倒数三个作为子文件夹名字。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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.strip('\n'))#生成拼接路径,strip去除readlines()读出的换行符
      os.mkdir(dirname1)
      print dirname1
      dirname2 = os.path.join(URL,month+line.strip('\n'),line[-3].strip('\n'))
      os.mkdir(dirname2)
      print dirname2
      dirname3 = os.path.join(URL,month+line.strip('\n'),line[-2].strip('\n'))
      os.mkdir(dirname3)
      print dirname3
      dirname4 = os.path.join(URL,month+line.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)





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
>>> ================================ 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()读行时的换行符,会报错:

1
2
3
4
5
6
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: : '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'






页: [1]
查看完整版本: python初学之生成文件夹