Product SiteDocumentation Site

10.3. Reading a file

To read the whole file at once use the read() method.

>>> f = open("sample.txt")
>>> f.read()
'I love Python\nPradeepto loves KDE\nSankarshan loves Openoffice\n'

If you call read() again it will return empty string as it already read the whole file. readline() can help you to read one line each time from the file.

>>> f = open("sample.txt")
>>> f.readline()
'I love Python\n'
>>> f.readline()
'Pradeepto loves KDE\n'

To read all the all the lines in a list we use readlines() method.

>>> f = open("sample.txt")
>>> f.readlines()
['I love Python\n', 'Pradeepto loves KDE\n', 'Sankarshan loves Openoffice\n']

You can even loop through the lines in a file object.

>>> f = open("sample.txt")
>>> for x in f:
...     print x,
...
I love Python
Pradeepto loves KDE
Sankarshan loves Openoffice

Let us write a program which will take the file name as the input from the user and show the content of the file in the console.

#!/usr/bin/env python
name = raw_input("Enter the file name: ")
f = open(name)
print f.read()
f.close()

In the last line you can see that we closed the file object with the help of close() method.
The output

[kd@kdlappy book]$ ./showfile.py
Enter the filename: sample.txt
I love Python
Pradeepto loves KDE
Sankarshan loves Openoffice