-1

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

wundolab
  • 177
  • 10
  • This is missing a lot of context like the rest of the script you want to use this in? Not certain how to answer without knowing how it will be used. – Tom Myddeltyn Nov 30 '20 at 20:34
  • filename.to_csv("filename.csv") It is a simulation script...but...this is the command for saving. Thank you for your time...It could be helpul the way to save with the input name – wundolab Nov 30 '20 at 20:37

2 Answers2

1

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

df.to_csv(filecsv_name + '.csv') 
David
  • 769
  • 1
  • 6
  • 28
  • yes I'using pandas...I'll try...and If I want to use the new name in all the script? suggestion? It is a file in which I save simulations ... I'm a noob in python XD – wundolab Nov 30 '20 at 20:40
  • if you want to use the name again just use the variable ```filecsv_name``` – David Nov 30 '20 at 20:41
  • NameError: name 'df' is not defined – wundolab Nov 30 '20 at 20:44
  • Yes, you will have to create a dataframe in order to save it as a csv. df is just the standard name for a dataframe in pandas. Without the rest of your code, I cannot help. perhaps post another question? df is just the variable you are converting to csv – David Nov 30 '20 at 20:47
  • I have: # Use the above list to create a DataFrame filename = pd.DataFrame(columns=columnNames)....to define df? – wundolab Nov 30 '20 at 20:48
0

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

wundolab
  • 177
  • 10