Get module filename python

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.

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

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

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

Get Module File Information in Python

In Python sometimes you need to figure out where a function lives on the hard disk, or what file is calling your function. The os module provides tools for getting file and directory information and the inspect module provides the ability to inspect the stack and see what module is calling your function.

Get file information about a module

The os module in Python provides many useful ways for getting the file name of where a module lives. There are functions to get file names, directory names, and get absolute paths. Check out this example:

# Example assumes this file is named test.py
# and lives in /home/nanodano/
# https://docs.python.org/3/library/os.path.html

import os

# Prints the full path of where the os.py module resides
print(os.__file__)


# The name of file where this print statement is written
print(__file__)
# test.py

# Get the full absolute path using os.path.abspath()
print(os.path.abspath(__file__))
# /home/nanodano/test.py

# Get the directory name of a file with os.path.dirname()
print(os.path.dirname(__file__))
# Relative to current directory
# Prints an empty string if being run from current directory
# Prints .. if being called from a deeper directory

# Combine to get absolute path of the directory containing the python file
print(os.path.abspath(os.path.dirname(__file__)))
# /home/nanodano

## Other functions that might be useful
# os.path.join() # Join directory names using system specific dir separator
# os.sep() # Path separator character (system specific)
# os.getcwd() # Full absolute path
# os.walk() # Generator to walk dirs recursively
# os.listdir() # Current dir or specific dir

Get module and file name of caller

In some cases, your function is getting called by code from other .py files. If you want to figure out where your function is being called from, you can inspect the stack. The inspect module provides a way to get this data.

import inspect

# Import this to other module and call it
def print_caller_info():
# Get the full stack
stack = inspect.stack()

# Get one level up from current
previous_stack_frame = stack[1]
print(previous_stack_frame.filename) # Filename where caller lives

# Get the module object of the caller
calling_module = inspect.getmodule(stack_frame[0])
print(calling_module)
print(calling_module.__file__)


if __name__ == '__main__':
print_caller_info()

Conclusion

After reading this, you should know how to get the relative and absolute filename of the current Python modules as well as modules that are calling your function.

Источник

How do I find the current module name in Python?

A module can find out its own module name by looking at the predefined global variable __name__. If this has the value '__main__', the program is running as a script.

Example

def main(): print('Testing…. ') ... if __name__ == '__main__': main()

Output

Modules that are usually used by importing them also provide a command-line interface or a selftest, and only execute this code after checking __name__.

The__name__ is an in-built variable in python language, we can write a program just to see the value of this variable. Here’s an example. We will check the type also −

Example

print(__name__) print(type(__name__))

Output

Example

def myFunc(): print('Value of __name__ = ' + __name__) if __name__ == '__main__': myFunc()

Output

Value of __name__ = __main__

Example

Now, we will create a new file Demo2.py. In this we have imported Demo and called the function from Demo.py.

import Demo as dm print('Running the imported script') dm.myFunc() print('\n') print('Running the current script') print('Value of __name__ = ' + __name__)

Output

Running the imported script Value of __name__ = Demo Running the current script Value of __name__ = __main__

Источник

Читайте также:  Arhangel ru card php
Оцените статью