If you are facing any issue in playing video please use Firefox browser.
Python Read Write Function In Python 2
In this lecture we will see that, How to work with file with read and write functions ?
In Python working in file is very easy, we don't need to export any external library for it.
If you want to store something in a file, so for that we will need to read file, that means first of all we have to open our file and whatever data we want to save we will write it in file.
Opening and closing of file
"open()" is use to open the file.
It returns file object.
Syntax for opening and closing file
fileName: Name of the file that we wants to open.
mode: 'r' (only for reading), 'w' (only for writing), 'a' (for append), 'r+w' (for read and write).
call f.close() to close it and free of any system resource taken up by the open file.
(If we open a file in writing mode, and search type of file do not exist, then Python will itself make a file of it in our project folder)
Reading and writing files
file.read(size) : this function is used to read a file's contents.
If size is omitted or negative then the entire content is returned.
If the end of the file has been reached, f.read() will return an empty string(' ').
f.readline() reads a single line from the file; a newline character (\\n) is left at the end of the string, India's only omitted on the last line of the file if the file doesn't end in a new line.
For reading lines from a file, you can loop over the file object.
This is memory efficient, fast, and leads to simple code :
for line in f:
f.write(string) write the contents of string to the file, returning the number of characters written.
Other types of objects need to be converted either to a string (in text mode) or a bytes object (in binary mode) before writing them.
Have a friend to whom you would want to share this course?