如果一个或两个文件不存在,如何处理该异常? - python

我正在尝试检查是否存在一个或两个文件,如下所示:

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?

我的问题是,如果一个或两个文件都不存在,如何传递异常?

python参考方案

如果不想使用内置os.path.exists()模块中的os.path.isfile()os.path,则必须使用两个try-except块:

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.

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

如何打印浮点数的全精度[Python] - python

我编写了以下函数,其中传递了x,y的值:def check(x, y): print(type(x)) print(type(y)) print(x) print(y) if x == y: print "Yes" 现在当我打电话check(1.00000000000000001, 1.0000000000000002)它正在打印:<…

Python:如何根据另一列元素明智地查找一列中的空单元格计数? - python

df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice','Jane', 'Alice','Bob', 'Alice'], 'income…