I l@ve RuBoard |
Simple File OperationsBefore 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.)
Now, using your favorite editor, open up c:\dat\hello.txt. You should see this:
File ModesThe Python file object supports the following modes:
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 DataWriting 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):
The read() method returns a string representing the contents of the file. |
I l@ve RuBoard |
No comments:
Post a Comment