with open("abc.txt", "w") as f:
f.write("Hello")
If we open a file using the with keyword, then the file closes automatically when the work is done. Even if an exception is raised during the operation, the file gets closed properly. So, it is more convenient to use the with keyword than the equivalent try…except…finally blocks.
How to read data from a file in Python?
In Python, we can read data from a file like the following:
with open("abc.txt", "r") as f:
print(f.read())
The f.read() function reads the entire content of a file and returns the content as a string. Alternatively, we can use f.read(n) to read n bytes from a file.
We can also use f.readline() function to read an entire line from a file. For example,
with open("abc.txt", "r") as f:
print(f.readline())
If no argument is given, then the f.readline() function returns an entire line. Alternatively, we can use f.readline(n) to read n bytes from a line.
How to read binary data from a file in Python?
In Python, we can open a file in “rb” mode and read binary data from the file. For example,
with open("abc.txt", "rb") as f:
print(f.read())
Let’s say the file abc.txt contains the bytes b’Hello’. So, the output of the program will be:
b'Hello'
Alternatively, we can also read, say 5 bytes from a file like the following:
with open("abc.txt", "rb") as f:
print(f.read(5))
How to write binary data to a file in Python?
In Python, we can open a file in “wb” mode and write binary data to the file. For example,








































0 Comments