i

Python Programming

Python File Read/Write

File object provides the set of access methods to make our lives happy. We would check how to use read() and write() methods to read / write files.

The write()-Method

The write()-method writes any string to an open file. It is important to note that Python-strings can binary data and not just text.

The write()-method does not add newline character ('\n') to the end of string.

Syntax                        >>>fileObject.write(string)

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

Example

The above method create foo.txt file / would write given content in that file and finally, it would close that file. If you open this file, it will have the following content.

Python is a good language.

Yeah its great!!

The read()-Method

The read()-method reads a string from an open file.

Syntax                        >>>>fileObject.read([count])

The passed parameter is number of bytes to be read from opened file. This method starts reading from beginning of file and if count is missing.

Example

Now take a file foo.txt, which we created above.

Output:

Read String is:python is