Choose the name to save a .csv file and use the name entered throughout the python script

2.4k views Asked by At

I want to save a .csv file using Python every time I want using a different name. So I wrote this code. In add of this, I want to use the new name in the rest of the script that after saving continues to run. How can I do this? Suggestions? Thank you very much.

from __future__ import division
from __future__ import print_function
from bigfloat import *
from builtins import *
from decimal import*
from math import*
import numpy as np
import time


# Initialize Cantera for numerical simulation

import pandas as pd
from pandas import DataFrame
import numpy as np
import time
import cantera as ct

print("Running Cantera version: {}".format(ct.__version__))
print("")

import matplotlib.pyplot as plt

plt.style.use('ggplot')
plt.style.use('seaborn-pastel')

plt.rcParams['axes.labelsize'] = 18
plt.rcParams['xtick.labelsize'] = 14
plt.rcParams['ytick.labelsize'] = 14
plt.rcParams['figure.autolayout'] = True



#################################################################

phi=1.2

Ti=900   # Kelvin

Pi=1.2   # Atm

#################################################################

# Load the kinetic mechanism for

gas = ct.Solution('tester.cti')

# Inlet gas conditions
reactorTemperature = Ti  #row[5] # Kelvin
reactorPressure = Pi*ct.one_atm  # in atm 
gas.set_equivalence_ratio(phi, 'H2:3', 'O2:3, N2:94, N2O:0.00005')
gas.TP= reactorTemperature, reactorPressure

# Mean Molecular Weight

MR=gas.mean_molecular_weight

print('')
print('Mean molecular weight for gas declared :', float(format(MR, '.3f')))
print('')

# Reactor parameters
residenceTime = 0.21 # s
reactorVolume = 113*(1e-2)**3  # m3

# Instrument parameters

# This is the "conductance" of the pressure valve and will determine its efficiency in 
# holding the reactor pressure to the desired conditions. 
pressureValveCoefficient = 0.001

# This parameter will allow you to decide if the valve's conductance is acceptable. If there
# is a pressure rise in the reactor beyond this tolerance, you will get a warning
maxPressureRiseAllowed = 0.01

# Simulation termination criterion
maxSimulationTime = 5  # seconds


# Definition of reservoirs
fuelAirMixtureTank = ct.Reservoir(gas)
exhaust = ct.Reservoir(gas)
env = ct.Reservoir(gas)

# Definition of Reactor
stirredReactor = ct.IdealGasReactor(gas, energy='on', volume=reactorVolume)

# Definition of an heat wall exchange
w=ct.Wall(stirredReactor, env, A=0.0113,  U=220)     

# Declaration of controllers

massFlowController = ct.MassFlowController(upstream=fuelAirMixtureTank,
                                           downstream=stirredReactor,
                                           mdot=MR*reactorPressure*reactorVolume/ct.gas_constant/gas.T/residenceTime)
                                           

pressureRegulator = ct.Valve(upstream=stirredReactor,
                             downstream=exhaust,
                             K=pressureValveCoefficient)

# Definition of reactorNetwork solver
reactorNetwork = ct.ReactorNet([stirredReactor])

# Now compile a list of all variables for which we will store data
columnNames = [stirredReactor.component_name(item) for item in range(stirredReactor.n_vars)]
columnNames = ['pressure'] + columnNames




filename        = input('filename: ')
filename       = str(filename)

print(filename)

df = pd.DataFrame(filename, columns= columnNames)

df.to_csv (eval(filename))

I want to save data in a file .csv in which I have ColumnNames as defined...how can I do? Best regards

2

There are 2 answers

0
wundolab On

I do not know why the administrators behave in a certain way, giving me negative votes and preventing me from asking questions. But, I really appreciate the usefulness of this forum and everyone's time. As it often happens in my questions, if I find the solution I will also post it. Also, I try to ask things that we have both personal and for everyone (especially for everyone). That said, I post the solution.

Remember that columnNames is defined to specify headers ando so data.

print(' Save time history data for time dependent profile as filename)')
print('-------------------------------------------------------- ')

filename       = input('filename: ')
filename        =  str(filename)

print(filename)

df=filename
df=pd.DataFrame(columns=columnNames)

df.to_csv(filename+ '.csv')

Thank you to all and to stackoverflow as ever

5
David On

If you are using pandas you can save as a csv in this way:

df.to_csv(filecsv_name + '.csv')