Table of Contents:
- Python is capable of handling or manipulating data stored in files.
- We can open a file using inbuilt
open()
function. - While opening a file, we have to pass different modes as a parameter to specify what we're trying to do with the file.
-
r
: Reading mode- The default mode.
- It allows you only to read the file, not to modify it.
- When using this mode the file must exist.
-
w
: Writing mode- It will create a new file if it does not exist, otherwise will erase the file and allow you to write to it.
-
a
: Append mode- It will write data to the end of the file.
- It does not erase the file, and the file must exist for this mode
-
rb
: Binary Reading mode- same as
r
but reading is forced in binary mode. - This is also a default choice.
- same as
-
wb
: Binary Writing mode- same as
w
but writing is forced in binary mode.
- same as
-
ab
: Binary Apend mode- same as
a
but appending is forced in binary mode.
- same as
-
r+
: Reading mode plus Writing mode at the same time- This allows you to read and write into files at the same time without having to use
r
andw
.
- This allows you to read and write into files at the same time without having to use
-
w+
: Writing mode plus Reading mode at the same time.- If the file does not exist, a new one is made. otherwise overwritten.
-
a+
: Apend mode- similar to
w+
- similar to
-
rb+
: Binary Reading mode- same as
r+
mode but forced in binary mode
- same as
-
wb+
: Binary Writing mode- same as
w+
mode but forced in binary mode
- same as
-
ab+
: Binary Apend mode- same as
a+
mode but forced in binary mode
- same as
- We use
open()
function to open the file. - We use
file.close()
method to close the file.
Basic Syntax:
file_obj = open("<filename>", "<mode>")
# do our stuff over here
file_obj.close()
file = open("my_file.txt", "r")
file.read()
file.close()
- If we open the file with
with
keyword, then we do not need to explicitly close the file. - It automatically closes the file whenever it goes out of the scope.
with open('my_file.txt', 'r') as f:
# do our stuff here
f.read()
print("At this point, the file is closed")
with open('my_file.txt', 'w') as f:
f.write("This is the content to the file.")
with open('my_file.txt', 'a') as f:
f.write("This is the appended content to the file.")
with open ('my_file.txt', 'r') as f:
for line in f:
print(line)
we can also achieve the same result using readlines()
method.
with open ('my_file.txt', 'r') as f:
for line in f.readlines():
print(line)