Jane Borges
Jane Borges

Reputation: 592

Read and save a csv file with the name of a variable

I have the following variable:

      Id_Sensor = 406

This variable value is used to read the input file and to save the output dataframe. According to the codes below:

      # Read archive csv
      df_Sensor = pd.read_csv('C:/User/Desktop/Data/SENSOR/PROJ01_406.csv')

      # Save the archive
      df_Sensor.to_csv('PROJ01_IDENTIF406_test.csv')

I would like the name ID sensor to be automatic when reading the file and when saving. Why do I need to write the number 406 manually. Is there a way to insert the value of a variable inside the functions pd.read_csv and to_csv?

Upvotes: 0

Views: 919

Answers (1)

John Gordon
John Gordon

Reputation: 33275

Lots of ways to do it. Take your pick!

Using % formatting:

df_Sensor = pd.read_csv('C:/User/Desktop/Data/SENSOR/PROJ01_%s.csv' % Id_Sensor)

Using .format():

df_Sensor = pd.read_csv('C:/User/Desktop/Data/SENSOR/PROJ01_{0}.csv'.format(Id_Sensor))

Using f-strings:

df_Sensor = pd.read_csv(f'C:/User/Desktop/Data/SENSOR/PROJ01_{Id_Sensor}.csv')

Upvotes: 6

Related Questions