TUTORIAL: Basic Python File I/O

  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6251
  • Loc: Seattle, WA

Post 3+ Months Ago

Introduction


Note: This tutorial assumes a basic knowledge of Python syntax.

In this tutorial you will learn how to read and write basic text files in Python.

Opening A File


To open a file, we use the open() function to create a file object. Open takes two arguments: the name of the file and the mode for which we'd like to open the file.

A file can be opened for reading ("r") or writing ("w"), just as with most other languages. Let's open up a file for reading:

PYTHON Code: [ Select ]
filename = "myfile.txt"
file = open(filename, "r")
  1. filename = "myfile.txt"
  2. file = open(filename, "r")


Reading From A File


Now that we've opened out file, let's read in the entire contents of the file and print them on standard output:

PYTHON Code: [ Select ]
contents = file.read()
print contents
  1. contents = file.read()
  2. print contents


We can also choose to read in the file as a list of lines, if we so desire:

PYTHON Code: [ Select ]
lines = file.readlines()
for line in lines:
    print line
  1. lines = file.readlines()
  2. for line in lines:
  3.     print line


Closing The File


We must close the file with close() once we are finished using it, otherwise other applications will not be able to access it. Python will automatically close the file when the script finishes executing, but its good practice to always explicitly close files:

PYTHON Code: [ Select ]
file.close()


Writing To A File


Writing to a file is just as simple as reading from it. Let's open a file, this time for writing ("w"), and write some text to it. If the file does not exist, it will be created:

PYTHON Code: [ Select ]
filename = "anotherfile.txt"
file = open(filename, "w")
file.write("Forks and spoons are obviously inferior.")
file.close()
  1. filename = "anotherfile.txt"
  2. file = open(filename, "w")
  3. file.write("Forks and spoons are obviously inferior.")
  4. file.close()


We can also write a list of lines to the file, just as we were able to read in a list of lines:

PYTHON Code: [ Select ]
lines = ["a line of text", "another line of text", "a third line"]
file.writelines(lines)
 
# or, alternatively:
 
for line in lines:
    file.writeline(line)
 
file.close()
  1. lines = ["a line of text", "another line of text", "a third line"]
  2. file.writelines(lines)
  3.  
  4. # or, alternatively:
  5.  
  6. for line in lines:
  7.     file.writeline(line)
  8.  
  9. file.close()


Appending To An Existing File


When we open a file in write mode ("w"), any contents of that file will be replaced by whatever we write to it. But in many cases, we simply want to add (append) to the existing contents of a file.

To append to an existing file, simply open the file in append mode ("a"):

PYTHON Code: [ Select ]
file = open(filename, "a")
file.write("some appended text")
file.close()
  1. file = open(filename, "a")
  2. file.write("some appended text")
  3. file.close()


Conclusion


You should now know how to do basic text file I/O in Python. You can consult the Python documentation for file objects for more information on the different methods available.

I always welcome questions or feedback about this tutorial. Simply post a reply or PM me; I'm glad to help!
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

Post Information

  • Total Posts in this topic: 1 post
  • Moderator: Tutorial Writers
  • Users browsing this forum: No registered users and 1 guest
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.