Import into Python a CSV File that has a Variable Name

In this short guide, you’ll see how to import into Python a CSV file that has a variable name.

The Example

Let’s say that you want to import into Python a CSV file, where the file name is changing on a daily basis.

For instance, the CSV file name may contain a date, which varies each day.

Assume that the CSV file is stored under the following path:

r“C:\Users\Ron\Desktop\sales_ + x1 + “.csv”

Where:

  • The part in yellow (the “r“) is placed to address special characters in the path, such as ‘\’
  • The portion highlighted in blue is the part of the path name that never changes
  • The part in green represents the variable x1 (in our case, it’s the date which varies every day)
  • The part in purple is the “.CSV” file extension which also doesn’t change

Note that the + signs are used to concatenate the different components in the path name. Also note that the variable (in green) should never be placed within quotes (while the non-variable portions, in blue and purple, should be placed within quotes).

Let’s say that you have the following data stored in a CSV file. And that the CSV file name contains the date of 23042024 (this date is your variable), so the full CSV file name is sales_23042024.

productpricedate
computer80023042024
tablet25023042024
printer10023042024

Here is the code to import the CSV file that has a variable name (note that you’ll need to change the path to reflect the location where the CSV file is stored on your computer):

import pandas as pd

x1 = str(input())

path = r"C:\Users\Ron\Desktop\sales_" + x1 + ".csv"

df = pd.read_csv(path)

print(df)

Notice that the code itself contains an input function to allow you to type your desired variable date before importing your file.

Running the Code in Python

(1) First, run the code in Python

(2) Then, type the date of 23042024

(3) Finally, press ENTER

This is the result that you’ll get:

    product  price      date
0  computer    800  23042024
1    tablet    250  23042024
2   printer    100  23042024

Let’s say that in the following day, you got a new CSV file, where the date is 24042024. The new CSV file name would be: sales_24042024.

productpricedate
keyboard12024042024
monitor45024042024

In that case, rerun the Python code, and then type the date of 24042024 and press ENTER.

You should see the next-date results:

    product  price      date
0  keyboard    120  24042024
1   monitor    450  24042024

Leave a Comment