码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-04-03 19:22:29      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:inpu   nsf   color   none   make   body   java   usr   bin   

 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()

 

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

标签:inpu   nsf   color   none   make   body   java   usr   bin   

原文地址:https://www.cnblogs.com/xuemanjiangnan/p/8710119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!