Course
Read Files
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Read Files
To programmatically read data from a file using Python, it must be opened first. Use the built-in
open()
functionfile object = open(file_name [, access_mode][, buffering])
Here are the parameter details −
file_name − The file_name argument is a string value that contains the name of the file that you want to access.
access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. This is an optional parameter and the default file access mode is read (r).
These two statements are identical
fo = open("foo.txt", "r")fo = open("foo.txt")
To read data from the opened file, use read() method of the File object. It is important to note that Python strings can have binary data apart from the text data.
Syntax
fileObject.read([count])
Parameters
- count − Number of bytes to be read.
Here, passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.
Example
# Open a filefo = open("foo.txt", "r")text = fo.read()print (text)
# Close the opened filefo.close()
It will produce the following output
Python is a great language.Yeah its great!!
Reading in Binary Mode
By default, read/write operation on a file object are performed on text string data. If we want to handle files of different other types such as media (mp3), executables (exe), pictures (jpg) etc., we need to add 'b' prefix to read/write mode.
Assuming that the test.bin file has already been written with binary mode.
f=open('test.bin', 'wb')data=b"Hello World"f.write(data)f.close()
We need to use 'rb' mode to read binary file. Returned value of read() method is first decoded before printing
f=open('test.bin', 'rb')data=f.read()print (data.decode(encoding='utf-8'))
It will produce the following output
Hello World
Read Integer Data from F ile
In order to write integer data in a binary file, the integer object should be converted to bytes by
to_bytes()
method.n=25n.to_bytes(8,'big')f=open('test.bin', 'wb')data=n.to_bytes(8,'big')f.write(data)
To read back from a binary file, convert the output of
read()
function to integer by using the from_bytes()
function.f=open('test.bin', 'rb')data=f.read()n=int.from_bytes(data, 'big')print (n)
Read Float Data from File
For floating point data, we need to use struct module from Python's standard library.
import structx=23.50data=struct.pack('f',x)f=open('test.bin', 'wb')f.write(data)
Unpacking the string from
read()
function to retrieve the float data from binary file.f=open('test.bin', 'rb')data=f.read()x=struct.unpack('f', data)print (x)
Using the r+ M ode
When a file is opened for reading (with 'r' or 'rb'), it is not possible to write data in it. We need to close the file before doing other operation. In order to perform both operations simultaneously, we have to add '+' character in the mode parameter. Hence 'w+' or 'r+' mode enables using
write()
as well as read()
methods without closing a file.The File object also supports the
seek()
function to rewind the stream to read from any desired byte position.Following is the syntax for
seek()
methodfileObject.seek(offset[, whence])
Parameters
- offset − This is the position of the read/write pointer within the file.
- whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.
Let us use the seek() method to show how to read data from a certain byte position.
Example
This program opens the file in w+ mode (which is a read-write mode), adds some data. The it seeks a certain position in file and overwrites its earlier contents with new text.
fo=open("foo.txt","r+")fo.seek(10,0)data=fo.read(3)print (data)fo.close()
It will produce the following output
rat
Python Simultaneous Read/Write
When a file is opened for writing (with 'w' or 'a'), it is not possible to read from it and vice versa. Doing so throws UnSupportedOperation error. We need to close the file before doing other operation.
In order to perform both operations simultaneously, we have to add '+' character in the mode parameter. Hence 'w+' or 'r+' mode enables using
write()
as well as read() methods without closing a file. The File object also supports the seek()
unction to rewind the stream to any desired byte position.The seek() Method
The method
seek()
sets the file's current position at the offset. The whence argument is optional and defaults to 0, which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.There is no return value. Note that if the file is opened for appending using either 'a' or 'a+', any
seek()
operations will be undone at the next write.If the file is only opened for writing in append mode using 'a', this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+').
If the file is opened in text mode using 't', only offsets returned by tell() are legal. Use of other offsets causes undefined behavior.
Note that not all file objects are seekable.
Syntax
Following is the syntax for
seek()
method fileObject.seek(offset[, whence])
Parameters
- offset − This is the position of the read/write pointer within the file.
- whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.
Let us use the
seek()
method to show how simultaneous read/write operation on a file can be done.The following program opens the file in w+ mode (which is a read-write mode), adds some data. The it seeks a certain position in file and overwrites its earlier contents with new text.
Example
# Open a file in read-write modefo=open("foo.txt","w+")fo.write("This is a rat race")fo.seek(10,0)data=fo.read(3)fo.seek(10,0)fo.write('cat')fo.seek(0,0)data=fo.read()print (data)fo.close()
Output
This is a cat race
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.