Skip to content

Commit 3a1626b

Browse files
authored
Merge pull request #694 from krishnajalan/main
Implement CSV to excel script
2 parents cbfe49c + 513d788 commit 3a1626b

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

csv_to_excel/README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Script to convert CSV -> excel
2+
3+
Script expect the user to pass path to CSV Or path to directory containing multiple CSV
4+
and saves the excel file at same dir as provided path
5+
6+
## install requirements/dependencies:
7+
8+
python -r requirements.txt
9+
10+
## how to use:
11+
12+
call the program using:
13+
`python main.py {filename or directory}`
14+
15+
file example: `python main.py test.csv`
16+
dir example: `python main.py dirContainingCSVs/`

csv_to_excel/main.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import pandas as pd
2+
import sys
3+
import os
4+
5+
args = sys.argv[1:] # get command line *args
6+
assert args, "No file/dir was provided" # raise error is no arg is passed
7+
8+
isdir = os.path.isdir(args[-1])
9+
10+
# If input is CSV file
11+
if not isdir:
12+
assert args[-1].endswith(".csv"), "Input file is not CSV; Provide CSV file"
13+
data = pd.read_csv(args[-1]) # load CSV data as Pd object
14+
data.to_excel(args[-1][:-4] + ".xlsx", index=None, header=True)
15+
del data
16+
17+
# If input is Directory containing multiple csv
18+
else:
19+
try:
20+
# remove "/" from end of directory is passed
21+
if args[-1][-1] == "/":
22+
args[-1] = args[-1][:-1]
23+
# create a dir to save the excel datasheet
24+
os.mkdir(args[-1] + "_excel")
25+
except Exception:
26+
pass
27+
for filename in os.listdir(args[-1]):
28+
if filename.endswith(".csv"):
29+
data = pd.read_csv(filename)
30+
data.to_excel(
31+
args[-1] + "_excel/" + filename[:-4] + ".xlsx"
32+
) # write as excel
33+
del data # delete the pandas DataFrame object
34+
35+
exit(0)

csv_to_excel/requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
pandas==1.3.3
2+
openpyxl==3.0.9

0 commit comments

Comments
 (0)