簡體   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