Home
Search
Python Path: os.path ExamplesUse path methods found in the os.path module. Test file existence, size and dates.
dot net perls
Path. A file system stores information about its files. With the os.path module in Python, we access this information. Many methods are available here.
We detect whether a file is present with path.exists. We read dates, get sizes and list file names. We split and join paths. We can even find a common prefix of 2 paths.
Exists. This example uses the path.exists method. We pass a string containing a file's location on the system disk. If the file does not exist, path.exists returns false.
Tip This method can be used to avoid IOErrors that occur when a program tries to open a file that does not exist.
IOError
Python program that uses exists
from os import path # See if this file exists. # ... Write a custom message based on the result. if path.exists("/enable1.txt"): print("File exists") else: print("File not found, sorry")
File exists
Getsize. How many bytes are in a file? There are several ways to get this information. We could read in the file and count the bytes. But the path.getsize() method is simpler.
Bytes The path.getsize method returns a numeric figure. This is the byte count of the target file.
Note The returned value is in bytes, not megabytes. To change the number to megabytes, we would need to divide it.
Numbers
Python program that uses getsize
from os import path # Get size of this text file. size = path.getsize("/enable1.txt") # Display the size in bytes. print(size)
1916146
Commonprefix. The path module includes a method called commonprefix. This method receives a list of paths. It scans these strings and returns the longest shared common prefix.
List, strings
Warning Commonprefix does no validation—the prefix may not be a valid path. Be careful with invalid data.
Here We create an empty list and then append three paths two it. Then, the commonprefix method returns the longest prefix.
Note It returns the name of the enclosing folder of all the files. It omits the nested folder.
Python program that uses commonprefix
from os import path # Add paths to a list. paths = [] paths.append("C:\directory\name") paths.append("C:\directory\image") paths.append("C:\directory\folder\index") # Get common prefix of the paths. prefix = path.commonprefix(paths) print(prefix)
C:\directory
List files. How can we get a list of the files in a directory? The os.listdir method is helpful here. It receives a directory path. It returns a list of the file names in the directory.
Tip There are just file names, not paths. To open these files, we must combine the file name with the path.
Python program that lists files in folder
import os # Get all files in this directory. list = os.listdir("C:\\programs\\") print(list)
['file.php', 'file.pl', 'file.py', 'file.rb']
Join. This method combines paths. It receives two or more string arguments and combines them in an "intelligent" way. It will, for example, add a slash to the end of one argument.
Tip We access the join method by using its complete, composite name os.path.join. This requires no "from" in the import directive.
Python program that uses join
import os # Join directory name not including slash. result = os.path.join("C:\\programs", "file.py") print(result) # Join directory name with trailing slash. result = os.path.join("C:\\programs\\", "file.py") print(result)
C:\programs\file.py C:\programs\file.py
Split. With path.split we can separate the "folder" from the "file name." Pass a path string to path.split. It returns a tuple with two parts.
First part The first part of the returned tuple is the folder path with no file name on it. The end slash is omitted.
Second part This is the file name. So it will be something like file.txt. It includes the extension.
Raw literals For file paths, please consider using raw string literals with an "r" prefix (unlike many of the examples on this page).
Python program that uses path.split
from os import path example = r"C:\programs\file.txt" # Use split on path. result = path.split(example) # The result has two parts. print("Result:", result) # The second part of the tuple is the file name. print("File name:", result[1])
Result: ('C:\\programs', 'file.txt') File name: file.txt
Timestamps. The path.getatime, path.getmtime and path.getctime methods get timestamps from files. These are the last-access time, the last-modified time, and (on Windows) the creation time.
Tip We get path timestamps, and convert them to dates. Please look for the example "File timestamps" in the Datetime page.
Datetime
A reference. The Python site is an ice reference and it should be used constantly when exploring new parts of Python. Here is the os.path material.
Summary. The file system provides useful information about files. The path methods in the os.path module are helpful for retrieving this information.
This influences IO performance. It also yields simpler Python code. Path methods should be used when possible for more reliable execution.
Home
© 2007-2021 sam allen. see site info on the changelog