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()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.31.125