reading-note

https://eng-ehabsaleh.github.io/reading-note/

View on GitHub

Reading and Writing Files in Python

Opening and Closing a File in Python

to open a file there is two way

the first way is to use with statement

note wish will close the file once it leaves the with block, even in cases of error. I highly recommend that you use the with statement as much as possible, as it allows for cleaner code and makes handling any unexpected errors easier for you.

with open('dog_breeds.txt', 'r') as reader:
    # Further file processing goes here

the second way is to use open and close method

This is done by invoking the open() built-in function. open() has a single required argument that is the path to the file.

you have to close the file after you open or it will not be close by it self

other thing that i should take about is the opening modes

with open('dog_breeds.txt', 'r') as reader:
which used for reading
with open('dog_breeds.txt', 'w') as reader:
which used for writing

Working With Bytes

Sometimes, you may need to work with files using byte strings. This is done by adding the ‘b’ character to the mode argument. All of the same methods for the file object apply. However, each of the methods expect and return a bytes object instead

ex

>>> with open('dog_breeds.txt', 'rb') as reader:
>>>     print(reader.readline())

Python Exceptions

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.

This exception error will crash the program if it is unhandled. The except clause determines how your program responds to exceptions.

In Python, the assert statement is used to continue the execute if the given condition evaluates to True. If the assert condition evaluates to False, then it raises the AssertionError exception with the specified error message