Checking for file and directory existence

If you want to make sure a file or directory exists (or it doesn't), the os.path module is what you need. Let's see a small example:

# files/existence.py
import os

filename = 'fear.txt'
path = os.path.dirname(os.path.abspath(filename))

print(os.path.isfile(filename)) # True
print(os.path.isdir(path)) # True
print(path) # /Users/fab/srv/lpp/ch7/files

The preceding snippet is quite interesting. After declaring the filename with a relative reference (in that it is missing the path information), we use abspath to calculate the full, absolute path of the file. Then, we get the path information (by removing the filename at the end) by calling dirname on it. The result, as you can see, is printed on the last line. Notice also how we check for existence, both for a file and a directory, by calling isfile and isdir. In the os.path module, you find all the functions you need to work with pathnames.

Should you ever need to work with paths in a different way, you can check out pathlib. While os.path works with strings, pathlib offers classes representing filesystem paths with semantics appropriate for different operating systems. It is beyond the scope of this chapter, but if you're interested, check out PEP428 (https://www.python.org/dev/peps/pep-0428/), and its page in the standard library.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.10.246