简体   繁体   English

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

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

Context:语境:

  1. Problem i am trying to solve is - Read a CSV file, check if a variable within CSV file is of certain value and do prints我要解决的问题是 - 读取 CSV 文件,检查 CSV 文件中的变量是否具有特定值并打印

Questions:问题:

  1. There might be a situation where file is marked as non-readable.可能存在文件被标记为不可读的情况。 If this happens, Would there be an exception?.如果发生这种情况,会有例外吗? If yes - How do i catch the exception?如果是 - 我如何捕捉异常?

  2. There could also be an exception if the file is not present.如果文件不存在,也可能存在异常。 So, the file not present exception comes first and then the file not readable exception comes later?那么,文件不存在异常首先出现,然后文件不可读异常出现在后面?

Code:代码:

# 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")

You can catch the error with two exceptions for files ( IOError, OSError ) read the below for more info https://www.tutorialspoint.com/python/python_exceptions.htm您可以通过两个文件异常( IOError、OSError )捕获错误,请阅读以下内容以获取更多信息https://www.tutorialspoint.com/python/python_exceptions.htm

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

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