The open() function is used to open files in our system, the filename is the name of the file to be opened.
The mode indicates, how the file is going to be opened "r" for reading, "w" for writing, "t" for a text mode. (default), "a" for a appending, "x" for a exclusive creation,"b" for a binary mode and "+" Open a file for updating (reading and writing)
The open function takes two arguments, the name of the file and and the mode for which we would like to open the file.
By default, when only the filename is passed, the open function opens the file in read mode.
f = open("website.txt") # equivalent to 'r' or 'rt' f = open("website.txt",'w') # write in text mode f = open("img.bmp",'r+b') # read and write in binary mode
f = open("test.txt",mode = 'r',encoding = 'utf-8')
To read the content of a file, we must open the file in reading mode.
There are various methods available for this purpose. We can use the read(size) method to read in size number of data. If size parameter is not specified, it reads and returns up to the end of the file.
>>> f = open("myfile.txt",'r',encoding = 'utf-8') >>> f.read(2)# read the first 4 data 'This' >>> f.read(2)# read the next 4 data ' is ' >>> f.read() # read in the rest till end of file 'my first file\nThis file\ncontains three lines\n' >>> f.read()# further reading returns empty sting ''
We can use
readline() method to read individual lines of a file. This method reads a file till the newline, including the newline character.
>>> f.readline() 'This is my first file\n' >>> f.readline() 'This file\n' >>> f.readline() 'contains three lines\n' >>> f.readline() ''
readlines() method returns a list of remaining lines of the entire file. All these reading method return empty values when end of file (EOF) is reached.
>>> f.readlines() ['This is my first file\n', 'This file\n', 'contains three lines\n']
In Python order to write into a file we need to open it in
write() 'w', append 'a' or exclusive creation 'x' mode.
with open("myfile.txt",'w',encoding = 'utf-8') as f: f.write("my first file\n") f.write("This file\n\n") f.write("contains three lines\n")
Closing a file will free up the resources that were tied with the file and is done using the
f = open("myfile.txt",encoding = 'utf-8') # perform file operations f.close()
This method is not entirely safe. If an exception occurs when we are performing some operation with the file, the code exits without closing the file.
A safer way is to use a try...finally block.
try: f = open("myfile.txt",encoding = 'utf-8') # perform file operations finally: f.close()
We don't need to explicitly call the
close() method. It is done internally.
with open("myfile.txt",encoding = 'utf-8') as f: # perform file operations