Files and Exceptions:

It’s simply not enough to process your list data in your code. You need to be able to get your data into your programs with ease, too. It’s no surprise then that Python makes reading data from files easy. Which is great, until you consider what can go wrong when interacting with data external to your programs…and there are lots of things waiting to trip you up! When bad stuff happens, you need a strategy for getting out of trouble, and one such strategy is to deal with any exceptional situations using Python’s exception handling mechanism.

Data is external to your program

Most of your programs conform to the input-process-output model: data comes in, gets manipulated, and then is stored, displayed, printed, or transferred.

Source: Google

We have learned how data is processed as well as displayed on screen. But what’s involved in getting data into your programs? Specifically, what’s involved in reading data from a file?

And!

How does Python read data from a file?

It’s all lines of text:The basic input mechanism in Python is line based: when read into your program from a text file, data arrives one line at a time.

Your programs can read information in from files, and they can write data to files. Reading from files allows you to work with a wide variety of information; writing to files allows users to pick up where they left off the next time they run your program. You can write text to files, and you can store Python structures such as lists in data files. Exceptions are special objects that help your programs respond to errors in appropriate ways. For example: if your program tries to open a file that doesn’t exist, you can use exceptions to display an informative error message instead of having the program crash.

Image for post
Image for post
Source:Google

Reading from a file

To read from a file your program needs to open the file and then read the contents of the file. You can read the entire contents of the file at once, or read the file line by line. The with statement makes sure the file is closed properly when the program has finished accessing the file.

Reading an entire file at once

filename = ‘text.txt’with open(filename) as f_obj:contents = f_obj.read()print(contents)
Image for post
Image for post

Reading line by line

Each line that’s read from the file has a newline character at the end of the line, and the print function adds its own newline character. The rstrip() method gets rid of the extra blank lines this would result in when printing to the terminal.

filename = ‘text.txt’with open(filename) as f_obj:for line in f_obj:print(line.rstrip())

The else block

The try block should only contain code that may cause an error. Any code that depends on the try block running successfully should be placed in the else block.

Using an else block

print(“Enter two numbers. I’ll divide them.”)x = input(“First number: “)y = input(“Second number: “)try: result = int(x) / int(y)except ZeroDivisionError:print(“You can’t divide by zero!”)else: print(result)
Image for post
Image for post

Reading from a file (cont.)

Storing the lines in a list:

filename = ‘text.txt’with open(filename) as f_obj:lines = f_obj.readlines()for line in lines:print(line.rstrip())print(type(lines))
Image for post
Image for post

Writing to a file

Passing the ‘w’ argument to open() tells Python you want to write to the file. Be careful; this will erase the contents of the file if it already exists. Passing the ‘a’ argument tells Python you want to append to the end of an existing file.

Writing to an empty file

filename = ‘text.txt’with open(filename, ‘w’) as f:f.write(“I love Python!”)

Writing multiple lines to an empty file

filename = ‘text.txt’with open(filename, ‘w’) as f:f.write(“I love python!\n”)f.write(“I love creating new games.\n”)

Appending to a file

filename = ‘text.txt’with open(filename, ‘a’) as f:f.write(“I also love working with data.\n”)f.write(“I love making websites as well.\n”)

File paths

When Python runs the open() function, it looks for the file in the same directory where the program that’s being executed is stored. You can open a file from a subfolder using a relative path. You can also use an absolute path to open any file on your system.

Opening a file from a subfolder

f_path = “python_programs/text.txt”with open(f_path) as f:lines = f.readlines()for line in lines:print(line.rstrip())

Failing silently

Sometimes you want your program to just continue running when it encounters an error, without reporting the error to the user. Using the pass statement in an else block allows you to do this.

Using the pass statement in an else block

f_names = [‘text.txt’, ‘program.txt’, ‘python_data.txt’, ‘data_text.txt’]for f_name in f_names:# Report the length of each file found.try:with open(f_name) as f:lines = f.readlines()except FileNotFoundError:# Just move on to the next file. Passelse:num_lines = len(lines)msg = f”{f_name} has {num_lines}”msg += “ lines.”print(msg)

Avoid bare except blocks

Exception-handling code should catch specific exceptions that you expect to happen during your program’s execution. A bare except block will catch all exceptions, including keyboard interrupts and system exits you might need when forcing a program to close. If you want to use a try block and you’re not sure which exception to catch, use Exception. It will catch most exceptions, but still allow you to interrupt programs intentionally.

Don’t use bare except blocks

try:# Do somethingexcept: pass

Use Exception instead

try:# Do somethingexcept Exception:pass

Printing the exception

try:# Do somethingexcept Exception as e:print(e, type(e))

Opening a file using an absolute path

f_path = “/home/aarti/python/text.txt”with open(f_path) as f:lines = f.readlines()

Opening a file on Windows Windows will sometimes interpret forward slashes incorrectly. If you run into this, use backslashes in your file paths.

f_path = “C:\Users\aarti\python\text.txt”with open(f_path) as f:lines = f.readlines()

The try-except block

When you think an error may occur, you can write a tryexcept block to handle the exception that might be raised. The try block tells Python to try running some code, and the except block tells Python what to do if the code results in a particular kind of error.

Handling the ZeroDivisionError exception

try:print(5/0)except ZeroDivisionError:print(“You can’t divide by zero!”)

Handling the FileNotFoundError exception

f_name = ‘text.txt’try:with open(f_name) as f:lines = f.readlines()except FileNotFoundError:msg = f”Can’t find file: {f_name}.”print(msg)

Knowing which exception to handle

It can be hard to know what kind of exception to handle when writing code. Try writing your code without a try block, and make it generate an error. The traceback will tell you what kind of exception your program needs to handle.

Thanks for giving your valuable time.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store