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
Best Answer
If you don't need it to be human-readable/editable, the easiest solution is to just use
pickle
.To write:
To read:
If you do need them to be human-readable, we need more information.
If
my_list
is guaranteed to be a list of strings with no embedded newlines, just write them one per line:If they're Unicode strings rather than byte strings, you'll want to
encode
them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.
Let's use
unicode-escape
here to solve both of the above problems at once:You can also use the 3.x-style solution in 2.x, with either the
codecs
module or theio
module:** TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use
codecs
; if not, useio
.