DEV Community

Idris Jimoh
Idris Jimoh

Posted on

Reading and Writing Files in Python

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 −

Syntax

fileObject.write(string)

Enter fullscreen mode Exit fullscreen mode

Here, passed parameter is the content to be written into the opened file.

Example

#!/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()

Enter fullscreen mode Exit fullscreen mode

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!!

Enter fullscreen mode Exit fullscreen mode

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.

Syntax

fileObject.read([count])

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

This produces the following result −

Read String is : Python is a great language.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)