
import osĪs you can see, the split() method returns head and tail values, and we printed the tail, which is the filename.

The tail is a filename, and the head is a filepath, and we are interested in the filename. The os.path.split() method returns head and tail. The os.path.split() method takes a path-like object representing a file system path. The os.path.split() is a built-in Python method used to split the pathname into a pair head and tail. Print(basename) Output app.py Using os.path.split() method To work with the ntpath module, you need to import it into your file and then use the ntpath.basename() function. You can also use it to handle Windows paths or other platforms.

The ntpath module provides os.path functionality on any platform. That is why you can use the ntpath module (which is equivalent to the os.path when running on windows) will work for all paths on all platforms. If you’re running your python script on Linux and try to process a classic Windows-style path, it will fail. The os.path module works fine for MacOS, but it does not work best for Linux OS or Windows. The universal solution to get filename from filepath When os.path.basename() method is used on a POSIX system to get the base name from a Windows-styled path the complete path will be returned. You can see from the output that we got exactly what we asked for. Path = '/Users/krunal/Desktop/code/pyt/app.py' To extract that from a filepath, use the os.path.basename() function. You can see from the filepath that the filename is app.py. path = '/Users/krunal/Desktop/code/pyt/app.py'

Under the OS module, we use the os.getcwd() method to return the path of the current directory. To return the directory you are currently in, we use the OS module to interact with the operating system. It is in these scenarios that the Python ‘get current directory’ command helps you know which directory you are in currently. Python would not be able to access the files if they aren't in the CWD. However, while trying to run multiple scripts or while handling files the Current Working Directory (CWD) is important. Similarly, to run a script, the working directory needs to be set to the directory containing the script. To retrieve a file in Python, you need to know the exact path to reach the file, in Windows, you can view a particular file’s path by right-clicking the File-> Properties-> General-> Location. These directories are present inside a root folder eg: C:\ or D:\ and each directory could contain files or subdirectories. In case you are new to programming, directories are nothing but folders. What are directories and how do they work? What are directories and how do they work?.In case you are here only for the solution of getting the current directory in Python, use this link. In this short tutorial, let us look at how you could use python to get the current directory and how to change the working directory.
