Ginger Slice
Ginger Slice

Reputation: 59

Pythonic way to save .py variables into series

I use a .py file with various input parameters to run a model. I need to save and log these parameters in a .csv for further reference. The .py file has a mixture of string and float variables and has several comments through it.

#  Years range from 2000 to 2015
year = 2000  # Year of star of range or single year if yearRange == 0
yearRange = 2015  # final year of range, set to 0 for single year
demand = 64800000

hydroCap = 5530
geoCap = 1400
windCap = 5900
windScl = 1
upgradedWindCapacityFactor = 1  # scales historical wind data based on estimates of 2050 average capacity factor
solarCap = 4900
solarScl = 1
renewableScl = 1.04

I have successfully saved these parameters so far using this code where inp is the imported .py file.

import inputs as inp

def save_inputs():
    inputVars = [[item, key] for item, key in vars(inp).items() if not item.startswith("__")]
    inputVars = pd.DataFrame.from_records(inputVars)
    inputS = pd.Series(inputVars[1])
    inputS.index = inputVars[0]
    inputS.to_csv(inp.directory + "inputFile.csv", line_terminator="\n")

Which outputs and exports the series

year                                                           2000
yearRange                                                      2015
demand                                                     64800000
hydroCap                                                       5530
geoCap                                                         1400
windCap                                                        5900
windScl                                                           1
upgradedWindCapacityFactor                                        1
solarCap                                                       4900
solarScl                                                          1
renewableScl                                                   1.04

However, my code seems convoluted. What would be a nicer way to do this?

Upvotes: 0

Views: 68

Answers (1)

4xy
4xy

Reputation: 3662

import csv
import inputs as inp

def save_inputs():
    with open(f'{inp.directory}inputFile.csv', 'w', newline='') as f:
        writer = csv.writer(f, delimiter='\t')
        writer.writerows(filter(lambda item: not item[0].startswith('_'), vars(inp).items()))

Note about newline parameter

If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.

Upvotes: 1

Related Questions