In Python, the IO module provides methods of three types of IO operations; raw binary files, buffered binary files, and text files. The canonical way to create a file object is by using the >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 2 function.
Any file operations can be performed in the following three steps:
- Open the file to get the file object using the built-in open() function. There are different access modes, which you can specify while opening a file using the open() function.
- Perform read, write, append operations using the file object retrieved from the >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 2 function.
- Close and dispose the file object.
Reading File
File object includes the following methods to read data from the file.
- read(chars): reads the specified number of characters starting from the current position.
- readline(): reads the characters starting from the current reading position up to a newline character.
- readlines(): reads all lines until the end of file and returns a list object.
The following >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 4 file will be used in all the examples of reading and writing files.
C:\myfile.txt
CopyThis is the first line. This is the second line. This is the third line.
The following example performs the read operation using the >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 5 method.
Example: Reading a File
Copy>>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object
Above, >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 6 opens the >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 7 in the default read mode from the current directory and returns a file object. >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 8 function reads all the content until EOF as a string. If you specify the char size argument in the >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 5 method, then it will read that many chars only. >>> f = open('C:\myfile.txt') # opening a file >>> line1 = f.readline() # reading a line >>> line1 'This is the first line. \n' >>> line2 = f.readline() # reading a line >>> line2 'This is the second line.\n' >>> line3 = f.readline() # reading a line >>> line3 'This is the third line.' >>> line4 = f.readline() # reading a line >>> line4 '' >>> f.close() # closing file object 0 will flush and close the stream.
Reading a Line
The following example demonstrates reading a line from the file.
Example: Reading Lines
Copy>>> f = open('C:\myfile.txt') # opening a file >>> line1 = f.readline() # reading a line >>> line1 'This is the first line. \n' >>> line2 = f.readline() # reading a line >>> line2 'This is the second line.\n' >>> line3 = f.readline() # reading a line >>> line3 'This is the third line.' >>> line4 = f.readline() # reading a line >>> line4 '' >>> f.close() # closing file object
As you can see, we have to open the file in >>> f = open('C:\myfile.txt') # opening a file >>> line1 = f.readline() # reading a line >>> line1 'This is the first line. \n' >>> line2 = f.readline() # reading a line >>> line2 'This is the second line.\n' >>> line3 = f.readline() # reading a line >>> line3 'This is the third line.' >>> line4 = f.readline() # reading a line >>> line4 '' >>> f.close() # closing file object 1 mode. The >>> f = open('C:\myfile.txt') # opening a file >>> line1 = f.readline() # reading a line >>> line1 'This is the first line. \n' >>> line2 = f.readline() # reading a line >>> line2 'This is the second line.\n' >>> line3 = f.readline() # reading a line >>> line3 'This is the third line.' >>> line4 = f.readline() # reading a line >>> line4 '' >>> f.close() # closing file object 2 method will return the first line, and then will point to the second line in the file.
Reading All Lines
The following reads all lines using the >>> f = open('C:\myfile.txt') # opening a file >>> line1 = f.readline() # reading a line >>> line1 'This is the first line. \n' >>> line2 = f.readline() # reading a line >>> line2 'This is the second line.\n' >>> line3 = f.readline() # reading a line >>> line3 'This is the third line.' >>> line4 = f.readline() # reading a line >>> line4 '' >>> f.close() # closing file object 3 function.
Example: Reading a File
Copy>>> f = open('C:\myfile.txt') # opening a file >>> lines = f.readlines() # reading all lines >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object
The file object has an inbuilt iterator. The following program reads the given file line by line until >>> f = open('C:\myfile.txt') # opening a file >>> line1 = f.readline() # reading a line >>> line1 'This is the first line. \n' >>> line2 = f.readline() # reading a line >>> line2 'This is the second line.\n' >>> line3 = f.readline() # reading a line >>> line3 'This is the third line.' >>> line4 = f.readline() # reading a line >>> line4 '' >>> f.close() # closing file object 4 is raised, i.e., the EOF is reached.
Example: File Iterator
Copyf=open('C:\myfile.txt') while True: try: line=next(f) print(line) except StopIteration: break f.close()
Use the for loop to read a file easily.
Example: Read File using the For Loop
Copyf=open('C:\myfile.txt') for line in f: print(line) f.close()
Output
This is the first line. This is the second line. This is the third line.
Reading Binary File
Use the 'rb' mode in the >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 2 function to read a binary files, as shown below.
Example: Reading a File
Copy>>> f = open('C:\myimg.png', 'rb') # opening a binary file >>> content = f.read() # reading all lines >>> content b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x08\x00\x00\x00\x08\x08\x06 \x00\x00\x00\xc4\x0f\xbe\x8b\x00\x00\x00\x19tEXtSoftware\x00Adobe ImageReadyq \xc9e\x00\x00\x00\x8dIDATx\xdab\xfc\xff\xff?\x03\x0c0/zP\n\xa4b\x818\xeco\x9c \xc2\r\x90\x18\x13\x03*8\t\xc4b\xbc\x01\xa8X\x07$\xc0\xc8\xb4\xf0>\\\x11P\xd7? \xa0\x84\r\x90\xb9\t\x88?\x00q H\xc1C\x16\xc9\x94_\xcc\x025\xfd2\x88\xb1\x04 \x88\x85\x90\x14\xfc\x05\xe2( \x16\x00\xe2\xc3\x8c\xc8\x8e\x84:\xb4\x04H5\x03 \xf1\\ .bD\xf3E\x01\x90\xea\x07\xe2\xd9\xaeB`\x82' >>> f.close() # closing file object
Writing to a File
The file object provides the following methods to write to a file.
- write(s): Write the string s to the stream and return the number of characters written.
- writelines(lines): Write a list of lines to the stream. Each line must have a separator at the end of it.
Create a new File and Write
The following creates a new file if it does not exist or overwrites to an existing file.
Example: Create or Overwrite to Existing File
Copy>>> f = open('C:\myfile.txt','w') >>> f.write("Hello") # writing to file 5 >>> f.close() # reading file >>> f = open('C:\myfile.txt','r') >>> f.read() 'Hello' >>> f.close()
In the above example, the >>> f = open('C:\myfile.txt') # opening a file >>> line1 = f.readline() # reading a line >>> line1 'This is the first line. \n' >>> line2 = f.readline() # reading a line >>> line2 'This is the second line.\n' >>> line3 = f.readline() # reading a line >>> line3 'This is the third line.' >>> line4 = f.readline() # reading a line >>> line4 '' >>> f.close() # closing file object 6 statement opens >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 7 in write mode, the >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 2 method returns the file object and assigns it to a variable >>> f = open('C:\myfile.txt') # opening a file >>> line1 = f.readline() # reading a line >>> line1 'This is the first line. \n' >>> line2 = f.readline() # reading a line >>> line2 'This is the second line.\n' >>> line3 = f.readline() # reading a line >>> line3 'This is the third line.' >>> line4 = f.readline() # reading a line >>> line4 '' >>> f.close() # closing file object 9. >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.readlines() # reading all lines >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 0 specifies that the file should be writable. Next, >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.readlines() # reading all lines >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 1 overwrites an existing content of the >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 7 file. It returns the number of characters written to a file, which is 5 in the above example. In the end, >>> f = open('C:\myfile.txt') # opening a file >>> line1 = f.readline() # reading a line >>> line1 'This is the first line. \n' >>> line2 = f.readline() # reading a line >>> line2 'This is the second line.\n' >>> line3 = f.readline() # reading a line >>> line3 'This is the third line.' >>> line4 = f.readline() # reading a line >>> line4 '' >>> f.close() # closing file object 0 closes the file object.
Appending to an Existing File
The following appends the content at the end of the existing file by passing >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.readlines() # reading all lines >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 4 or >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.readlines() # reading all lines >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 5 mode in the >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 2 method.
Example: Append to Existing File
Copy>>> f = open('C:\myfile.txt','a') >>> f.write(" World!") 7 >>> f.close() # reading file >>> f = open('C:\myfile.txt','r') >>> f.read() 'Hello World!' >>> f.close()
Write Multiple Lines
Python provides the >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.readlines() # reading all lines >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 7 method to save the contents of a list object in a file. Since the newline character is not automatically written to the file, it must be provided as a part of the string.
Example: Write Lines to File
Copy>>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 0
Opening a file with "w" mode or "a" mode can only be written into and cannot be read from. Similarly "r" mode allows reading only and not writing. In order to perform simultaneous read/append operations, use "a+" mode.
Writing to a Binary File
The >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.read() # reading a file >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 2 function opens a file in text format by default. To open a file in binary format, add >>> f = open('C:\myfile.txt') # opening a file >>> lines = f.readlines() # reading all lines >>> lines 'This is the first line. \nThis is the second line.\nThis is the third line.' >>> f.close() # closing file object 9 to the mode parameter. Hence the f=open('C:\myfile.txt') while True: try: line=next(f) print(line) except StopIteration: break f.close() 0 mode opens the file in binary format for reading, while the f=open('C:\myfile.txt') while True: try: line=next(f) print(line) except StopIteration: break f.close() 1 mode opens the file in binary format for writing. Unlike text files, binary files are not human-readable. When opened using any text editor, the data is unrecognizable.
The following code stores a list of numbers in a binary file. The list is first converted in a byte array before writing. The built-in function bytearray() returns a byte representation of the object.