简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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