-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoXLSX.py
68 lines (58 loc) · 1.84 KB
/
toXLSX.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
'''Converts csv/tsv files to a single xlsx file'''
from argparse import ArgumentParser
from datetime import datetime
from glob import glob
import os
import pandas
import unixpath
class XLSxconverter():
def __init__(self, args):
self.infiles = []
self.outfile = args.o
self.data = {}
self.__setInfiles__(args.i)
def __setInfiles__(self, infiles):
# Stores input file(s) in list
print("\n\tLocating input file(s)...")
if os.path.isfile(infiles):
self.infiles = [infiles]
else:
infiles = unixpath.checkDir(infiles)
for i in ["*.csv", "*.tsv", "*.txt"]:
self.infiles.extend(glob(infiles + i))
def __setData__(self, infile):
# Reads file into data frame
d = None
rows = []
name = unixpath.getFileName(infile)
with open(infile, "r") as f:
for line in f:
line = line.strip()
if d:
rows.append(line.split(d))
else:
d = unixpath.getDelim(line)
head = line.split(d)
self.data[name] = pandas.DataFrame(rows, columns = head)
def getInput(self):
# Reads input from files into pandas data frames
for i in self.infiles:
print(("\tReading input from {}...").format(os.path.split(i)[1]))
self.__setData__(i)
def writeXLSX(self):
# Writes data dict to xlsx
print(("\tWriting data to {}...").format(os.path.split(self.outfile)[1]))
with pandas.ExcelWriter(self.outfile) as writer:
for k in self.data.keys():
self.data[k].to_excel(writer, sheet_name = k)
def main():
start = datetime.now()
parser = ArgumentParser("Converts csv/tsv files to a single xlsx file.")
parser.add_argument("-i", help = "Path to input file or directory of csv/tsv/txt files to convert.")
parser.add_argument("-o", help = "Path to output file.")
c = XLSxconverter(parser.parse_args())
c.getInput()
c.writeXLSX()
print(("\tTotal runtime: {}\n").format(datetime.now() - start))
if __name__ == "__main__":
main()