- Python – Get Filename from Path with Examples
- How to get the filename from a path in Python?
- 1. Using os module
- Filename from os.path.basename()
- Filename from os.path.split()
- 2. Using pathlib module
- Author
- Python make file name
- # Table of Contents
- # Create a file name using Variables in Python
- # Creating a file name that contains an integer
- # Creating a file name with a timestamp
- # Create a file name using Variables with the addition operator
- # Create a file name using Variables using str.format()
- # Additional Resources
Python – Get Filename from Path with Examples
In this tutorial, we will look at how to get the filename from a path using Python.
How to get the filename from a path in Python?
There are a number of ways to get the filename from its path in python. You can use the os module’s os.path.basename() function or os.path.split() function. You can also use the pathlib module to get the file name.
Let look at the above-mentioned methods with the help of examples. We will be trying to get the filename of a locally saved CSV file in python.
1. Using os module
The os module comes with a number of useful functions for interacting with the file system. You can use the following functions from the os to get the filename.
Filename from os.path.basename()
The os.path.basename() function gives the base filename from the passed path. For example, let’s use it to get the file name of a CSV file stored locally.
import os # the absoulte path of the file file_path = r"C:\Users\piyush\Documents\Projects\movie_reviews_data\IMDB Dataset 5k.csv" # get the filename print(os.path.basename(file_path))
You can see that we get the filename along with its extension as a string. To get the filename without its extension you can simply split the text on “.” and take the first part.
# filename without extension print(os.path.basename(file_path).split(".")[0])
You might also be interested in knowing how to Get File size using Python
Filename from os.path.split()
You can also use the os.path.split() function to get the filename. It is used to split the pathname into two parts – head and tail, where the tail is the last pathname component and the head is everything leading up to that. For example, for the path a/b/c.txt , the tail would be c.txt and the head would be a/b
Let’s now use it to find the filename of the CSV file from its path.
# the absoulte path of the file file_path = r"C:\Users\piyush\Documents\Projects\movie_reviews_data\IMDB Dataset 5k.csv" # split the file path head, tail = os.path.split(file_path) # get the filename print(tail)
You can see that the tail gives us the filename. Let’s now go ahead and see what do we have in the head part.
# show the path head print(head)
C:\Users\piyush\Documents\Projects\movie_reviews_data
The head contains the part of the file path leading up to the filename. Note that the os.path.split() function determines the head and tail based on the occurrence of the last directory separator \ or / depending on the OS. For example, if the path ends in a separator it will give an empty string as the tail.
For more on the os.path.split() function, refer to its documentation.
2. Using pathlib module
For python versions 3.4 and above, you can also use the pathlib module to interact with the file system in python. Among other things, you can use it to get the filename from a path. For example, let’s get the filename of the same CSV file used above.
from pathlib import Path # the absoulte path of the file file_path = r"C:\Users\piyush\Documents\Projects\movie_reviews_data\IMDB Dataset 5k.csv" # get the filename print(Path(file_path).name)
You can see that we get the correct filename using the name attribute of Path .
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel.
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Author
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts
Python make file name
Last updated: Feb 22, 2023
Reading time · 3 min
# Table of Contents
# Create a file name using Variables in Python
Use a formatted string literal to create a file name using variables, e.g. f’.txt’ .
Formatted string literals enable us to include expressions and variables inside of a string by prefixing the string with f .
Copied!file_name = 'example' print(f'file_name>.txt') # 👉️ example.txt with open(f'file_name>.txt', 'w', encoding='utf-8') as f: f.write('first line' + '\n') f.write('second line' + '\n')
We used a formatted string literal to create a file name using variables.
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .
Copied!var1 = 'bobby' var2 = 'hadz' result = f'var1>var2>.csv' print(result) # 👉️ bobbyhadz.csv
Make sure to wrap expressions in curly braces — .
An advantage of f-strings is that they automatically take care of converting non-string values to strings.
# Creating a file name that contains an integer
Here is an example where we create a file name that contains an integer.
Copied!file_name = 'example' integer = 1234 print(f'file_name>_integer>.txt') # 👉️ example_1234.txt with open( f'file_name>_integer>.txt', 'w', encoding='utf-8' ) as f: f.write('first line' + '\n') f.write('second line' + '\n')
Formatted string literals also enable us to use expressions inside the curly braces.
# Creating a file name with a timestamp
Here is an example that uses the time.time() method to construct a file name.
Copied!import time timestamp = int(time.time()) file_name = 'example' print(f'file_name>_timestamp>.txt') # 👉️ example_1665817197.txt with open( f'file_name>_timestamp>.txt', 'w', encoding='utf-8' ) as f: f.write('first line' + '\n') f.write('second line' + '\n')
We used the time.time() method to get the number of seconds since the epoch.
You can also directly call a function between the curly braces.
# Create a file name using Variables with the addition operator
An alternative approach is to use the addition (+) operator.
The addition (+) operator can be used to concatenate strings with strings stored in variables.
Copied!import csv file_name = 'example' with open( file_name + '.csv', 'w', newline='', encoding='utf-8' ) as csvfile: csv_writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow(['Bobby', 'Hadz', 'Com'])
When the addition (+) operator is used with strings, it concatenates them.
Copied!print('ab' + 'cd') # 👉️ abcd
However, when you use the addition operator, you have to make sure that the values on the left and right-hand sides are strings.
If the variable stores an integer, use the str() class to convert it to a string.
Copied!file_name = 123456 result = str(file_name) + '.csv' print(result) # 👉️ 123456.csv
This is necessary because the values on the left and right-hand sides of the addition operator need to be of compatible types.
This is not the case when using f-strings because they automatically take care of the conversion for us.
# Create a file name using Variables using str.format()
You can also use the str.format() method.
The string the method is called on can contain replacement fields specified using curly braces.
Copied!file_name = 'example' print('<>.txt'.format(file_name)) # 👉️ example.txt with open( '<>.txt'.format(file_name), 'w', encoding='utf-8' ) as f: f.write('first line' + '\n') f.write('second line' + '\n')
The str.format method performs string formatting operations.
Copied!first = 'bobby' last = 'hadz' result = "<>_<>.txt".format(first, last) print(result) # 👉️ "bobby_hadz.txt"
The string the method is called on can contain replacement fields specified using curly braces <> .
The replacement fields can also contain the name of a keyword argument.
Copied!first = 'bobby' last = 'hadz' result = "_.txt".format(f=first, l=last) print(result) # 👉️ "bobby_hadz.txt"
You can also call functions to specify a value for a replacement field.
Copied!import time first = 'bobby' result = "<>_<>.txt".format(first, int(time.time())) print(result) # 👉️ "bobby_1665817957.txt"
Notice that the str.format() method automatically takes care of converting the integer to a string when formatting.
Which approach you pick is a matter of personal preference. I’d use a formatted string literal because I find them quite readable and intuitive.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
- Split a String into multiple Variables in Python
- How to assign Print output to a Variable in Python
- Not all arguments converted during string formatting (Python)
- TypeError: Strings must be encoded before hashing (Python)
- io.UnsupportedOperation: not readable/writable Python Error
- How to clear all variables in a Python script
- How to unzip a .gz file using Python [5 simple Ways]
- How to create a Zip archive of a Directory in Python
- How to update a JSON file in Python [3 Ways]
- How to recursively delete a Directory in Python
- pygame.error: video system not initialized [Solved]
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.