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 ...

Get Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.