Reputation: 700
I'm trying to check if one or two files exist like this:
def check_files_if_exist():
try:
f1 = open(file1)
f1.close()
f2 = open(file2)
f2.close()
except:
#how to pass exception if one or two files does not exist?
My question is how do I pass an exception if of one or both files does not exist?
Upvotes: 2
Views: 1953
Reputation: 6276
def check_files_if_exist():
try:
f1 = open(file1)
f1.close()
f2 = open(file2)
f2.close()
except:
pass # if you want to stop the whole function, you can use "return False" here.
I don't know the scenario of the author. If you want to just stop the function, you can use return False
. But if you still want to execute some function even the file1
and file2
doesn't exists, you can use pass to ignore the exception.
Upvotes: 0
Reputation: 82
use os.path.isfile(path)
to check whether file exists, without any exception.
import os
def check_files_if_exist(path1, path2):
return os.path.isfile(path1) and os.path.isfile(path2)
or
import os
def check_files_if_exist(*paths):
return all(os.path.isfile(path) for path in paths)
Upvotes: 0
Reputation: 1574
If you don't want to use os.path.exists()
or os.path.isfile()
from the built-in os.path
module, you'll have to use two try-except blocks:
def check_files_if_exists(...):
try:
f1 = open(...)
f1.close()
except:
return False # Return False because the path doesn't exist
try:
f2 = open(...)
f2.close()
except:
return False # Return False because the path doesn't exist
return True # This only occurs when both files exist.
Upvotes: 0
Reputation: 7045
You can directly check if a file exist by using the pathlib.Path
module. It comes with python.
from pathlib import Path
p = Path('/path/to/file.txt')
if p.exists():
# open file...
with p.open('r') as file:
for line in file:
line = line.strip()
# Do something here...
Upvotes: 1