The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files.
The write() Method
The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string −
Here, passed parameter is the content to be written into the opened file.
#!/usr/bin/python # Open a file fo = open("foo.txt", "wb") fo.write( "Python is a great language.\nYeah its great!!\n") # Close opend file fo.close()
The above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have following content.
Python is a great language. Yeah its great!!
The read() Method
The read() method reads a string from an open file. It is important to note that Python strings can have binary data. apart from text data.
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.
Let's take a file foo.txt, which we created above.
#!/usr/bin/python # Open a file fo = open("foo.txt", "r+") str = fo.read(10); print "Read String is : ", str # Close opend file fo.close()
This produces the following result −
Read String is : Python is a great language.