visit
When we would like to check if a path is empty or not, we will want to know if it is a file or a directory, as this affects the approach we want to use. Let's say we have two placeholder variables dirpath
and filepath
identifying a local directory and file:
dirpath="/mnt/f/code.books/articles/python"
filepath="/mnt/f/code.books/articles/python/code/file_dir.py"
os.path
os.path
provides us with the isfile()
and isdir()
functions to effortlessly distinguish between a file and the given directory:
import os
dirpath="/mnt/f/code.books/articles/python"
filepath="/mnt/f/code.books/articles/python/code/file_dir.py"
os.path.isfile(dirpath) # False
os.path.isdir(dirpath) # True
os.path.isfile(filepath) # True
os.path.isdir(filepath) # False
pathlib
Python 3.4 introduced the pathlib
module, which provides an object-oriented interface for working with file systems.
pathlib
simplifies working with file systems compared to os
or os.path
.
The Path
class of the pathlib
module accepts a path as an argument and returns a Path
object, which can be easily queried or chained with methods and attributes:
from pathlib import Path
dirpath="/mnt/f/code.books/articles/python"
filepath="/mnt/f/code.books/articles/python/code/file_dir.py"
Path(dirpath).is_file() # False
Path(dirpath).is_dir() # True
Path(filepath).is_file() # True
Path(dirpath).is_file() # False
$ touch emptyfile
Or on Windows:
$ type nul > emptyfile
emptyfile="/mnt/f/code.books/articles/python/emptyfile"
nonemptyfile="/mnt/f/code.books/articles/python/onebytefile"
$ ls -l -rwxrwxrwx 1 root root 0 Sep 10 18:06 emptyfile -rwxrwxrwx 1 root root 1 Sep 10 18:08 onebytefile $ file emptyfile emptyfile: empty $ file onebytefile onebytefile: very short file (no magic)
There is also another solution that uses os.stat
. You can read more about that .