繁体   English   中英

Python | 如何捕获文件不可读的异常

[英]Python | How to catch file not readable exceptions

语境:

  1. 我要解决的问题是 - 读取 CSV 文件,检查 CSV 文件中的变量是否具有特定值并打印

问题:

  1. 可能存在文件被标记为不可读的情况。 如果发生这种情况,会有例外吗? 如果是 - 我如何捕捉异常?

  2. 如果文件不存在,也可能存在异常。 那么,文件不存在异常首先出现,然后文件不可读异常出现在后面?

代码:

# reader module from csv will allow us to read the csv file.
# aliasing it to csv_reader so that its more readable on what the variable does.
from csv import reader as csv_reader

# Encasing the code in try and catch block to catch potential exceptions dealing with accessing file.
try:
    # Opening the file and getting a filehandle
    with open("input.csv") as file_handle:

        # reading the csv file using the csvreader
        people = csv_reader(file_handle)

        # accessing the headers (i.e. column names) for the file.
        # How would this come in handy? -
        #   Later when we create a temporary dictionary, we can access the data using the column names as keys
        headers = next(people)

        # going thru each of the data-row of the csv
        for row in people:
            # Zipping the headers (column names) and data for the row to create dictionary
            #
            # Dictionary which will look like -
            #
            # Key   | Value
            # --------------
            # "name" - "John"
            # "age"  - "30"
            # "city" - "Boston"
            #
            person = dict(zip(headers, row))

            # Now that we have a python dictionary, we can access the column names using the dictionary keys
            if int(person["age"]) >= 30:
                print("Name:{name}, City:{city}".format(name=person["name"], city=person["city"]))

except FileNotFoundError:
    print("Given file isnt present")

您可以通过两个文件异常( IOError、OSError )捕获错误,请阅读以下内容以获取更多信息https://www.tutorialspoint.com/python/python_exceptions.htm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM