Skip to content

Commit 7b2555e

Browse files
authored
CSV reader/writer
1 parent a7ae40a commit 7b2555e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Read_Write_CSV.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import csv
2+
3+
# ==========================================================
4+
# Function for reading a CSV file into a dictionary format
5+
# ==========================================================
6+
7+
def read_variables_csv(csvfile):
8+
"""
9+
Builds a Python dictionary object from an input CSV file.
10+
Helper function to read a CSV file on the disk, where user stores the limits/ranges of the process variables.
11+
"""
12+
dict_key={}
13+
try:
14+
with open(csvfile) as f:
15+
reader = csv.DictReader(f)
16+
fields = reader.fieldnames
17+
for field in fields:
18+
lst=[]
19+
with open(csvfile) as f:
20+
reader = csv.DictReader(f)
21+
for row in reader:
22+
lst.append(float(row[field]))
23+
dict_key[field]=lst
24+
25+
return dict_key
26+
except:
27+
print("Error in reading the specified file from the disk. Please make sure it is in current directory.")
28+
return -1
29+
30+
# ===============================================================
31+
# Function for writing the design matrix into an output CSV file
32+
# ===============================================================
33+
34+
def write_csv(df,filename):
35+
"""
36+
Writes a CSV file on to the disk from the internal Pandas DataFrame object i.e. the computed design matrix
37+
"""
38+
try:
39+
filename=filename+'.csv'
40+
df.to_csv(filename)
41+
except:
42+
return -1

0 commit comments

Comments
 (0)