Reading a file line by line

We can iterate over a file in a line-by-line way:

>>> with open('test.txt', 'r') as file:>>>    for line in file:>>>        print(line)

In this example, we join all these functionalities with exception-management when we are working with files.

You can find the following code in the create_file_exceptions.py file:

def main():    try:        with open('test.txt', 'w') as file:            file.write("this is a test file")    except IOError as e:        print("Exception caught: Unable to write to file", e)    except Exception as e:        print("Another error occurred ", e)    else:        print("File written to successfully") if __name__ == '__main__':    main()

Get Mastering Python for Networking and Security now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.