One of the most frequently used operations when you are learning a programming language would be open a file. This tutorial shows you how to manupinate different kinds of file.

How to read a Text File

Let's kick off by opening a text file "file.txt" with the built in function "open". In the following example with default setting, this file is opened in read-only model. 
# the open keyword opens a file in read-only mode by default
f = open("/home/jeffery/file.txt")
# read all the lines in the file and return them in a list
lines = f.readlines()

You can also use an extra parameter to be explicit.
f = open("/home/jeffery/file.txt", mode='r')

The “r” means to just read the file. You can also open a file in “rb” (read binary), “w” (write), “a” (append), or “wb” (write binary). Note that if you use either “w” or “wb”, Python will overwrite the file, if it exists already or create it if the file doesn’t exist.
If you want to read the file, you can use the following methods:
  • read - reads the whole file and returns the whole thing in a string
  • readline - reads the first line of the file and returns it as a string
  • readlines – reads the entire file and returns it as a list of strings
You can also read a file with a loop, like this:
f = open("/home/jeffery/file.txt", mode='r')
for line in f:
    print line

How to write a Text File

In this case, you first have to change the mode to "w" or "a" when you open the file. 
# the open keyword opens a file in write mode by default
f = open("/home/jeffery/wfile.txt", mode="w")
# Write string str to file.
str = "the content you want to write"


If you want to write the file, you can use the following methods:
  • write - write(str) -> None.  Write string str to file.  Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.
  • writelines – writelines(sequence_of_strings) -> None.  Write the strings to the file. 
If you know more about Python Files IO, please refer to


Popular Posts