In this short guide, you’ll see how to import into Python a CSV file that has a variable name.
Example – Importing into Python a CSV File that has a Variable Name
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.
For example, let’s suppose that a CSV file is stored under the following path:
r‘C:\Users\Ron\Desktop\sales_’ + x1 + ‘.csv’
- The part highlighted 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 27042019 (this date is your variable), so the full CSV file name is sales_27042019.
Here is the code to import the CSV file that has a variable name (note that you’ll need to change the path name 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 27042019
(3) Finally, press ENTER
This is the result that you’ll get:
product price date 0 computer 800 27042019 1 tablet 250 27042019 2 printer 100 27042019
Let’s say that in the following day, you got a new CSV file, where the date is 28042019. The new CSV file name would be: sales_28042019.
In that case, rerun the Python code, and then type the date of 28042019 and press ENTER.
You should see the next-date results:
product price date 0 keyboard 120 28042019 1 monitor 450 28042019
You just saw how to import into Python a CSV file that has a variable name. In this guide, you used a date variable. However, you can apply the same concepts for different types of variables.
Additionally, similar principles would apply if you try to import different file types, such as Excel files.