-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfec.py
81 lines (69 loc) · 2.2 KB
/
fec.py
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
import csv
def readFecFiles(files):
result = {}
for f in files:
fileId = f.split('-')[1].replace('.txt', '')
result[fileId] = {}
with open(f) as csvfile:
for i, row in enumerate(csvfile):
splitRow = row.replace('\r\n', '').split('\t')
if i == 6: result[fileId]['headers'] = [header+'_'+fileId for header in splitRow]
if i > 6: result[fileId][splitRow[0]] = splitRow
return result
def mergeFecFiles(files):
merged = {}
files = readFecFiles(files)
for f, data in files.items():
for k, v in data.items():
merged[k] = []
for f, data in files.items():
for k, v in data.items():
if v:
merged[k].extend(v)
# writeRowCsv(merged)
writeDictCsv(merged)
def writeDictCsv(merged):
result = {}
for otu in merged:
result[otu] = {}
for i, header in enumerate(merged['headers']):
for otu in merged:
try:
if otu:
result[otu][header] = merged[otu][i]
except Exception as e:
pass
with open('dictWriter.csv', 'w') as csvfile:
fieldnames = sorted(merged['headers'])
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for k in sorted(result):
writer.writerow(result[k])
def writeRowCsv(merged):
# merged = rowsToDict(merged)
with open('merged.csv', 'wb') as csvfile:
csvWriter = csv.writer(csvfile)
csvWriter.writerow(merged['headers'])
for k in sorted(merged):
if k != 'headers' and merged[k]:
csvWriter.writerow(merged[k])
if __name__ == '__main__':
import os, sys, glob
import timeit
timerStart = timeit.default_timer()
files = []
try:
#Get all .txt files in working dir
for txtFile in glob.glob("*.txt"):
files.append(txtFile)
mergeFecFiles(files)
except Exception, e:
print 'Could not open files in dir. Exception: ', e
finally:
timerStop = timeit.default_timer()
if files:
for i, f in enumerate(files):
print i+1, ' - ', f
print i+1, 'files merged in ', round(timerStop - timerStart, 3), 's'