- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileDeal.py
More file actions
Latest commit
319 lines (280 loc) · 11.7 KB
/
Copy pathFileDeal.py
File metadata and controls
319 lines (280 loc) · 11.7 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#coding:utf-8
importcsv
importcodecs
importxml.dom.minidom
importos
importsys
default_encoding="utf-8"
if(default_encoding!=sys.getdefaultencoding()):
reload(sys)
sys.setdefaultencoding(default_encoding)
classFILEDEAL:
defCSVToListFun(self, filePath):
'''
文件转dict
'''
lists= []
withopen(filePath, 'r') asf:
try:
reader=csv.reader(( (line.replace('\0','') forlineinf) ) )
except:
return (False,"读取文件({0})错误".format(filePath))
fori, rowinenumerate(reader):
printrow
ifi<=1:
lists.append(row)
iflen(lists) !=2orlen(lists[0]) ==0orlen(lists[0]) !=len(lists[1]):
return (False, "文件({0})信息数量错误".format(filePath))
lists[0][0] =lists[0][0].replace(codecs.BOM_LE, "")
return (True, lists)
defcsvToChangedDatasList(self,orgFilesPath):
ChangedDatasList= []
foriinrange(len(orgFilesPath)):
orgFilePath=orgFilesPath[i]
fileName=os.path.splitext(os.path.basename(orgFilePath))[0]
tempKeyList= []
tempValuesList= []
#with open(orgFilePath, 'r') as f:
withcodecs.open(orgFilePath, 'rb',encoding='utf-16') asf:
# for line in f:
# print line#.replace('\0', '').replace(codecs.BOM_LE, "").decode('gbk','ignore').encode('gbk')
try:
reader=csv.reader(((line.replace('\0', '') forlineinf)))#.replace(codecs.BOM_LE, "").decode("utf-8")
printreader
except:
return (False, "读取文件({0})错误".format(orgFilePath))
fori, rowinenumerate(reader):
iflen(row)>0:
ifi==0:
tempKeyList=row
tempKeyList[0] =tempKeyList[0].replace(codecs.BOM_LE, "")
else:
tempValuesList.append(row)
printrow
forjinrange(len(tempValuesList)):
dic=dict(zip(tempKeyList, tempValuesList[j]))
dic["MMZZEERROO"] =fileName+ (str(j) ifj>0else"")
ChangedDatasList.append(dic)
return (True, ChangedDatasList)
defend(self, nameGZ, saveDir, valueSplit, middenDatas, orgFilesPath):
suc, dicList=self.csvToChangedDatasList(orgFilesPath)
ifnotsuc:
return (suc, dicList)
else:
# 检查命名规则:
iflen(nameGZ) ==0:
return (False, u"请设置xml文件命名规则保存")
iflen(dicList) >1andnameGZ.find("#") ==-1andnameGZ.find("*") ==-1and (nameGZ.find("{") ==-1ornameGZ.find("}") ==-1):
return (False, u"文件数量与xml文件命名规则不匹配")
foriinrange(len(dicList)):
dic=dicList[i]
# 替换内容的\
iflen(valueSplit) >0anddic.has_key(valueSplit):
str=dic[valueSplit]
tempList=str.split("\\")
iflen(tempList) >0:
dic[valueSplit] =tempList[len(tempList) -1]
# 修改文件名
dic["MMZZEERROO"] =self.changeName(nameGZ, dic, i)
# 多个内容+++
forjinrange(len(middenDatas)):
middenData=middenDatas[j]
valueStr=""
keyMapList=middenData.keyMap.split("+")
forkinrange(len(keyMapList)):
ifdic.has_key(keyMapList[k]):
valueStr+=dic[keyMapList[k]]
dic[middenData.key] =valueStr
# 去除多余的
for (x, v) indic.items():
ifx=="MMZZEERROO":
continue
tempBool=False
foryinrange(len(middenDatas)):
ddd=middenDatas[y]
ifddd.key==x:
tempBool=True
ifnottempBool:
deldic[x]
#修改key
forminrange(len(middenDatas)):
tempData=middenDatas[m]
iftempData.key!=tempData.keyCopyanddic.has_key(tempData.key):
dic[tempData.keyCopy] =dic[tempData.key]
deldic[tempData.key]
#xml
doc=xml.dom.minidom.Document()
root=doc.createElement("DOCCONTENT")
root.setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance")
doc.appendChild(root)
for (k,v)indic.items():
ifk=="MMZZEERROO":
continue
nodeName=doc.createElement(k)
printv
nodeName.appendChild(doc.createTextNode(v))
root.appendChild(nodeName)
path=saveDir+"\\"+dic["MMZZEERROO"]+".xml"
withopen(path, 'w') asfp:
try:
doc.writexml(fp, indent='\t', addindent='\t', newl='\n', encoding="utf-8")
except:
return (False, "写入文件({0})错误".format(path))
return (True, "ok")
defchangeName(self,orgName,dic, i):
newName=orgName;
for (k,v) indic.items():
ifk=="MMZZEERROO":
continue
str="{"+k+"}"
newName=newName.replace(str,v)
MMZZEERROO=dic["MMZZEERROO"]
newName=newName.replace('*', MMZZEERROO)
newName=newName.replace('#', "{0}".format(i+1))
returnnewName
# 原始文件转化为可读文件
defgetMiddenDatas(self, lists):
temp= []
foriinrange(len(lists[0])):
temp.append(ListData(lists[0][i], lists[1][i]))
returntemp
# 把源文件(多个)转化为
defchange(self, orgFilesPath):
pass
defListToXML(self, paths, middleDatas, csvFilesPathList):
csvLists= []
forminrange(len(csvFilesPathList)):
suc, rep=self.CSVToListFun(csvFilesPathList[m])
ifnotsuc:
return (suc, rep)
else:
csvLists.append(self.getMiddenDatas(rep))
forninrange(len(paths)):
path=paths[n]
doc=xml.dom.minidom.Document()
root=doc.createElement("DOCCONTENT")
root.setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance")
doc.appendChild(root)
foriinrange(len(middleDatas)):
data=middleDatas[i]
nodeName=doc.createElement(data.keyCopy)
valueStr=""
keyMapList=data.keyMap.split("+")
forjinrange(len(keyMapList)):
tempStr=keyMapList[j]
forkinrange(len(csvLists[n])):
iftempStr==csvLists[n][k].key:
valueStr+=csvLists[n][k].value
nodeName.appendChild(doc.createTextNode(valueStr))
root.appendChild(nodeName)
withopen(path, 'w') asfp:
try:
doc.writexml(fp, indent='\t', addindent='\t', newl='\n', encoding="utf-8")
except:
return (False, "写入文件({0})错误".format(path))
return (True, "ok")
classListData(object):
def__init__(self, key, value):
self.key=key
self.value=value
self.keyCopy=key
self.keyMap=key
classChangedData(object):
def__init__(self, key, value, fileName):
self.key=key
self.value=value
self.fileName=fileName
# def ListToXML1(self,paths, middleDatas):
# for m in range(len(paths)):
# path = paths[m]
#
# doc = xml.dom.minidom.Document()
# root = doc.createElement("DOCCONTENT")
# root.setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance")
# doc.appendChild(root)
# #print middleDatas
# for i in range(len(middleDatas)):
# data = middleDatas[i]
# nodeName = doc.createElement(data.keyCopy)
# valueStr = ""
# keyMapList = data.keyMap.split("+")
# for j in range(len(keyMapList)):
# tempStr = keyMapList[j]
# for k in range(len(middleDatas)):
# if tempStr == middleDatas[k].key:
# valueStr += middleDatas[k].value
# nodeName.appendChild(doc.createTextNode(valueStr))
# root.appendChild(nodeName)
# fp = open(path, 'w')
# doc.writexml(fp, indent='\t', addindent='\t', newl='\n', encoding="utf-8")
# print "ok"
# def TxtToListFun(self, filePath):
# '''
# 文件转dict
# '''
# if filePath:
# file_object = codecs.open(filePath, "r")
# try:
# text = file_object.read()
# print text
# file_object.close()
# except:
# return (False,"读取文件({0})错误".format(filePath))
# print self.strToDictFun(text)
# return (False, "文件路径为空")
#
# else:
# return (False, "文件路径为空")
#
# def strToDictFun(self, str):
# print("%s",str)
# # if str[0] == ';':
# # str = str[1:]
# # if str[len(str)-1] == ';':
# # str = str[:len(str)-1]
# list = str.split(';')
# for i in range(len(list)):
# print list[i].decode('utf-8','ignore')
# return 43
classCnEncoding():
'''The encoding converter'''
def__init__(self, st, encoding=''):
'''
Initial the converter. 'st' could be an str or unicode object.
'encoding' refers the original encoding.
If do not know anything about the encoding,
use the default value or leave it blank.
'''
ifisinstance(st, unicode):
self._encoding='utf-8'
self._st=st.decode('utf-8')
elifisinstance(st, str):
ifencoding=='':
self._encoding=guess_coding(st)
else:
self._encoding=encoding
self._st=st
printself._st
else:
raiseValueError('%s is not a str nor unicode object.'%st)
def__str__(self):
returnself._st
def__unicode__(self):
returnself._st.decode(self._encoding)
defto_encode(self, encoding='utf-8'):
'''
return an printable str object in specific encoding.
'''
returnself._st.decode(self._encoding).encode(encoding)
defguess_coding(st):
'''Guess the codepage by try-except'''
fits_coding= ['utf-8', 'gbk', 'gb18030']
ifnotisinstance(st, str):
raiseValueError('%s is not a str object.'%st)
forcodeinfits_coding:
try:
st.decode(code)
returncode
exceptUnicodeDecodeError:
pass
return'unknow'