Reading and writing data using Python's input and output functionality  Hot PDF Print E-mail
Tag it:
Delicious
Furl it!
Digg
NewsVine
Reddit
YahooMyWeb
Technorati
Articles Reviews Python
Written by Adi Bach   
Saturday, 10 February 2007

{mos_sb_discuss:36}

In this article, you learn how to work with files. First, we review a simple way to output data in Python, using the print statement, then learn about the file object, which is used by Python programs to read and write data to a file.


The different modes with which a file can be opened are demonstrated, and the article concludes by showing how to read and write a binary file.

Reading, writing, and Python

In the previous articles in the "Discover Python" series, you learned about the basic Python data types and some of the container data types, such as the tuple, string, and list.

Other articles discussed the conditional and looping features of the Python language and how they work together with the container data types to simplify programming tasks.

The last basic step involved in writing programs is to read data from and write data to a file. After reading this article, you'll be able to check learning this skill off your to-do list.

Simple output

Throughout this series, you've written (output) data using the print statement, which by default writes the expression as a string to the screen (or console window). This is demonstrated in Listing 1, which repeats your first "Hello, World!" Python program with some minor tweaks.


Listing 1. Simple output


>>> print "Hello World!"
Hello World!
>>> print "The total value is = $", 40.0*45.50

The total value is = $ 1820.0

>>> print "The total value = $%6.2f" % (40.0*45.50)

The total value = $1820.00

>>> myfile = file("testit.txt", 'w')

>>> print >> myfile, "Hello World!"

>>> print >> myfile, "The total value = $%6.2f" % (40.0*45.50)

>>> myfile.close()

As this example shows, writing data is easy with the print statement. First, the example outputs a simple string. Then it creates and outputs a compound string, created using the string formatting technique.

Read more


User reviews

There are no user reviews for this item.

Add new review




Powered by jReviews

Last Updated ( Friday, 08 June 2007 )
 
< Prev   Next >