In this short guide, you’ll see how to import into Python a CSV file that has a variable name. This is especially useful when the file name changes regularly, such as when it includes a date.
The Example
Suppose you need to import a CSV file into Python, but the file name changes every day.
For example, the CSV file name may include a date value that varies daily.
Assume the CSV file is stored under a path structured like this:
r"C:\Users\Alex\Documents\sales_" + x1 + ".csv"
Where:
- The
ris used to handle special characters in the path, such as backslashes (\). - The portion
"C:\Users\Alex\Documents\sales_"is the fixed part of the file path that does not change. - The variable
x1represents the changing part of the file name (in this example, the date). - The
".csv"is the file extension, which remains constant.
The plus (+) Signs are used to concatenate different parts of the string. Notice that the variable x1 should not be placed inside quotes, while the fixed portions of the string must be enclosed in quotes.
Now, assume that you have the following data stored in a CSV file. The file name contains the date 23042024, so the complete file name is:
sales_23042024.csv
| product | price | date |
|---|---|---|
| computer | 800 | 23042024 |
| tablet | 250 | 23042024 |
| printer | 100 | 23042024 |
Below is the Python code to import a CSV file that has a variable name. You will need to modify the folder path according to your system:
import pandas as pd
x1 = str(input("Enter the date (DDMMYYYY): "))
file_path = r"C:\Users\Alex\Documents\sales_" + x1 + ".csv"
df = pd.read_csv(file_path)
print(df)The code uses the input() function so that you can manually enter the date before importing the file. This allows the script to dynamically construct the file name based on your input.
Running the Code in Python
- First, run the Python script.
- When prompted, type the date:
23042024. - Press ENTER.
You will receive the following output:
product price date
0 computer 800 23042024
1 tablet 250 23042024
2 printer 100 23042024
Now, suppose that on the next day, you receive a new CSV file with the date 24042024. The new file name would be:
sales_24042024.csv
And the file contains:
| product | price | date |
|---|---|---|
| keyboard | 120 | 24042024 |
| monitor | 450 | 24042024 |
To import this new file:
- Rerun the Python script.
- Enter
24042024when prompted. - Press ENTER.
You will then see:
product price date
0 keyboard 120 24042024
1 monitor 450 24042024
By using a variable inside the file path, you can easily manage files that follow a consistent naming pattern. This approach is practical for daily reports, logs, automated exports, and any workflow where file names change systematically.
