Course Content

If you are facing any issue in playing video please use Firefox browser.

Course Content

Description

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

 

open(fileName,mode)

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.

 

file=open('Test.txt','w')

(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)

file.close()

 

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:

print(line, end=")

 

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.

FAQs

Share With Friend

Have a friend to whom you would want to share this course?

Download The Apps

Code Scan or Download the app
Google Play Store
297K+ Downloads
4.5 Rating
10K+ Reviews
  • Learn anywhere on the go
  • Get regular updates about your enrolled or new courses
  • Share content with your friends
  • Evaluate your progress through practice tests
  • No internet connection needed
  • Enroll for the webinar and join at the time of the webinar from anywhere