Tuesday, October 27, 2009

Simple File Operations




I l@ve RuBoard









Simple File Operations


Before we begin our tour of files, we'll create a directory, c:\dat, where we'll put the data file we'll be working with throughout the chapter.


In Python, file I/O is built into the language, so working with files doesn't require an API or library. You just make a call to the intrinsic (built-in) open() function, which returns a file object. The typical form of open() is open(filename, mode).


Say, for example, that you want to open a file in c:\dat and write "Hello World" to it. Here's how to do that. (Start up the interactive interpreter and follow along.)



>>> file = open("c:\\dat\\hello.txt", "w")
>>> file.write("Hello World ")
>>> file.write("Hello Mars ")
>>> file.write("Hello Jupiter ")
>>> file.close()

Now, using your favorite editor, open up c:\dat\hello.txt. You should see this:



Hello World Hello Mars Hello Jupiter


Determining the File Object Type


To see the type of a file object, enter



>>> file = open("\\dat\\test.dat","w")
>>> type(file)

Under Jython and Jython you get



<jclass org.python.core.PyFile at 2054104961>

Under Python (a.k.a CPython) you get



<type 'file'>


File Modes


The Python file object supports the following modes:



  • Write�"w", "wb"


  • Read�"r", "rb"


  • Read and write�"r+", "r+b"


  • Append�"a", "ab"



The "b" appended to the mode signifies binary, which is necessary under Windows and Macintosh operating systems to work with binary files. You don't need binary mode with Jython because its code executes in the context of the Java Virtual Machine (JVM), which in this case is like a virtual operating system sitting atop the base operating systems, making them behave alike. You don't need binary mode, either, if you're running CPython under UNIX



Persisted Data


Writing to files without reading them doesn't do you much good unless you're creating a report of some kind. If you want to persist data so you can use it later, you have to be able to read it back into the program. Here's how we read the data that we wrote in the first example (please follow along):



>>> file = open("\\dat\\hello.txt", "r")
>>> file.read()
'Hello Mars Hello Jupiter'
>>> file.close()

The read() method returns a string representing the contents of the file.









    I l@ve RuBoard



    No comments:

    Post a Comment