If the reason you're checking is so you can do something like if file_exists: open_it()
, it's safer to use a try
around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.
If you're not planning to open the file immediately, you can use os.path.isfile
Return True
if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.
import os.path
os.path.isfile(fname)
if you need to be sure it's a file.
Starting with Python 3.4, the pathlib
module offers an object-oriented approach (backported to pathlib2
in Python 2.7):
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
To check a directory, do:
if my_file.is_dir():
# directory exists
To check whether a Path
object exists independently of whether is it a file or directory, use exists()
:
if my_file.exists():
# path exists
You can also use resolve(strict=True)
in a try
block:
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists
shutil
has many methods you can use. One of which is:
from shutil import copyfile
copyfile(src, dst)
# 2nd option
copy(src, dst) # dst can be a folder; use copy2() to preserve timestamp
- Copy the contents of the file named
src
to a file named dst
. Both src
and dst
need to be the entire filename of the files, including path.
- The destination location must be writable; otherwise, an
IOError
exception will be raised.
- If
dst
already exists, it will be replaced.
- Special files such as character or block devices and pipes cannot be copied with this function.
- With
copy
, src
and dst
are path names given as str
s.
Another shutil
method to look at is shutil.copy2()
. It's similar but preserves more metadata (e.g. time stamps).
If you use os.path
operations, use copy
rather than copyfile
. copyfile
will only accept strings.
Best Solution
When looking for file attributes for all files in a directory, and you are using Python 3.5 or newer, use the
os.scandir()
function to get a directory listing with file attributes combined. This can potentially be more efficient than usingos.listdir()
and then retrieve the file attributes separately:The
DirEntry.stat()
function, when used on Windows, doesn't have to make any additional system calls, the file modification time is already available. The data is cached, so additionalentry.stat()
calls won't make additional system calls.You can also use the
pathlib
module Object Oriented instances to achieve the same:On earlier Python versions, you can use the
os.stat
call for obtaining file properties like the modification time.st_mtime
is a float value on python 2.5 and up, representing seconds since the epoch; use thetime
ordatetime
modules to interpret these for display purposes or similar.Do note that the value's precision depends on the OS you are using:
If all you are doing is get the modification time, then the
os.path.getmtime
method is a handy shortcut; it uses theos.stat
method under the hood.Note however, that the
os.stat
call is relatively expensive (file system access), so if you do this on a lot of files, and you need more than one datapoint per file, you are better off usingos.stat
and reuse the information returned rather than using theos.path
convenience methods whereos.stat
will be called multiple times per file.