The os.path module allows us to easily work with, well, our operating system! The path module let’s us use file paths in different ways, including allowing us to get a file’s extension. Using os.path in Python to Get a File’s Extension
HOW TO CHECK MAC FILE EXTENSIONS HOW TO
Want to learn more? Want to learn how to use the pathlib library to automatically rename files in Python? Check out my in-depth tutorial and video on Towards Data Science! Now that we’ve taken a look at how to use pathlib in Python to get a file extension, let’s explore how we can do the same using the os.path module. This will let Python know to not use the backslashes as escape characters. But how do you do this? Simply prefix your string with a r, like this r'some string'. When you’re working with Windows, however, the file paths operate a little differently.īecause of this, when using Windows, create your file path as a “raw” string. This method works well for both Mac and Linux computers. When we assigned this to a variable named extension, we printed it, getting. After we did this, we can access different attributes, including the. We can see here that we passed a file’s path into the Path class, creating a Path object. Let’s see how we can use the pathlib library in Python to get a file’s extension: # Get a file's extension using pathlibįile_path = "/Users/datagy/Desktop/Important Spreadsheet.xlsx"Įxtension = pathlib.Path(file_path).suffix When we load our file’s path into a Path object, we can access specific attributes about the object by using its built-in properties. The pathlib library comes with a class named Path, which we use to create path-based objects.
Because of this, it makes perfect sense that the library would have the way of accessing a file’s extension. The Python pathlib library makes it incredibly easy to work with and manipulate paths. Using Python Pathlib to Get a File’s Extension