December 2018
Beginner to intermediate
796 pages
19h 54m
English
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.pyimport osfilename = 'fear.txt'path = os.path.dirname(os.path.abspath(filename))print(os.path.isfile(filename)) # Trueprint(os.path.isdir(path)) # Trueprint(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. ...
Read now
Unlock full access