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

Posted xuemanjiangnan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()

 

以上是关于python 文件夹内容与txt文件转换的主要内容,如果未能解决你的问题,请参考以下文章

python怎么把json文件转换成字符串

编写一个程序, 将 a.txt 文件中的单词与 b.txt 文件中的 单词交替合并到 c.txt 文件中, a.txt 文件中的单词用回车符 分隔, b.txt 文件中用回车或空格进行分隔。(代码片段

python 读取文件转换为列表

python中怎么比较文件名字符与文件指定位置内容字符是不是一致?

python 将txt文件转换成字典

python文件中内容转换为字典