python 文件夹内容与txt文件转换

 1 #!/usr/bin/python3
 2 # 文件名:ProjectTransfer.py
 3 
 4 import os
 5 class ProjectTransfer:
 6     def __init__(self, txtFilePath='D:/src.txt', srcPath='D:/mhi', srcPathTo='D:/mhi2', contentTypes=('.java','.xml','.jsp','.properties'), nameTypes=('.js','.css')):
 7         self.txtFilePath = txtFilePath
 8         self.srcPath = srcPath
 9         self.contentTypes = contentTypes
10         self.nameTypes = nameTypes
11         self.srcPathTo = srcPathTo
12     
13     def file2Txt(self, filePath, txtf):   
14         files = os.listdir(filePath) 
15         for f in files:
16             cf = filePath + '/' + f
17             if not os.path.isdir(cf):
18                 if os.path.splitext(f)[1] in self.contentTypes:
19                     txtf.write('#BeginFile:' + f + '\n')
20                     txtf.write('#FilePath:' + cf + '\n')
21                     with open(cf, encoding='utf-8') as inputf:
22                         txtf.writelines(iter(inputf))
23                     txtf.write('\n#EndFile:' + f + '\n')
24                 elif os.path.splitext(f)[1] in self.nameTypes :
25                     txtf.write('#BeginFile:' + f + '\n')
26                     txtf.write('#FilePath:' + cf + '\n')
27                     txtf.write('#EndFile:' + f + '\n')
28             else:
29                 self.file2Txt(cf, txtf)
30                 
31     def txt2File(self):
32         f = None
33         with open(self.txtFilePath, 'r', encoding='utf-8') as txtf:
34             for line in txtf:
35                 if line.startswith('#BeginFile:'):
36                     pass
37                 elif line.startswith('#FilePath:'):
38                     filePath = line[10:].replace(self.srcPath, self.srcPathTo)[:-1]
39                     if(f and not f.closed):
40                         f.close()
41                     dirname=os.path.dirname(filePath)
42                     if not os.path.exists(dirname):
43                         os.makedirs(dirname)
44                     f = open(filePath, 'w', encoding='utf-8')
45                 elif line.startswith('#EndFile:'):
46                     f.close()
47                 else:
48                     f.write(line)
49         
50                 
51 trans = ProjectTransfer()
52 if os.path.exists(trans.txtFilePath):
53     os.remove(trans.txtFilePath)
54 with open(trans.txtFilePath, 'a', encoding='utf-8') as txtf:
55     trans.file2Txt(trans.srcPath, txtf)
56     
57 trans.txt2File()

 

posted @ 2018-04-03 17:59  雪漫江南  阅读(366)  评论(0)    收藏  举报