Sat 4 Sep 2010
When I began learning Python, one of the first things I needed to know how to do was open a file. Now, the term “open a file” can mean different things depending on the context. Sometimes it means to actually open the file with Python and read from it, like with a text file. Other times, it means “to open the file in its default program”; and sometimes it means, “open the file in the program I specify”. So, when you go looking for how to do the latter two, you need to know how to ask Google just the right question or all you’ll end up with is learning how to open and read a text file.
In this article, we’re going to cover all three and we’ll also show how to open (or run) programs that are already installed on your PC. Why? Because that topic is also one of the first things I needed to learn and it uses some of the same techniques.
How to Open a Text File
Let’s start by learning how to open a file with Python. In this case, what we mean is to actually use Python to open it and not some other program. For that, we have two choices (in Python 2.x): open or file. Let’s take a look and see how it’s done!
# the open keyword opens a file in read-only mode by default f = open("path/to/file.txt") # read all the lines in the file and return them in a list lines = f.readlines() f.close()
As you can see, it’s really quite easy to open and read a text file. You can replace the “open” keyword with the “file” keyword and it will work the same. If you want to be extra explicit, you can write the open command like this instead:
f = open("path/to/file.txt", mode="r")
The “r” means to just read the file. You can also open a file in “rb” (read binary), “w” (write), “a” (append), or “wb” (write binary). Note that if you use either “w” or “wb”, Python will overwrite the file, if it exists already or create it if the file doesn’t exist.
If you want to read the file, you can use the following methods:
- read – reads the whole file and returns the whole thing in a string
- readline – reads the first line of the file and returns it as a string
- readlines – reads the entire file and returns it as a list of strings
You can also read a file with a loop, like this:
f = open("path/to/file.txt") for line in f: print line f.close()
Pretty cool, huh? Python rocks! Now it’s time to take a look at how to open a file with another program.
Open a file with its own program
Python has a simple method for opening a file with its default program. It goes something like this:
import os os.startfile(path)
Yes, it’s that easy, if you’re on Windows. If you’re on Unix or Mac, you’ll need the subprocess module or “os.system”. Of course, if you’re a real geek, then you probably have multiple programs that you might want to use to open a specific file. For example, I might want to edit my JPEG file with Picasa, Paint Shop Pro, Lightroom, Paint.NET or a plethora of other programs, but I don’t want to change my default JPEG editing program. How do we solve this with Python? We use Python’s subprocess module! Note: If you want to go old school, you can also use os.popen* or os.system, but subprocess is supposed to supersede them.
import subprocess pdf = "path/to/pdf" acrobatPath = r'C:\Program Files\Adobe\Reader 9.0\Reader\AcroRd32.exe' subprocess.Popen("%s %s" % (acrobatPath, pdf))
You can also write the last line like this: subprocess.Popen([acrobatPath, pdf]). Suffice it to say, using the subprocess module is also a breeze. There are many other ways to use the subprocess module, but this is one of its primary tasks. I usually use it to open a specific file (like above) or to open a program for me with specific arguments applied. I also use subprocess’s “call” method, which causes the Python script to wait for the “called” application to complete before continuing. You can also communicate with the processes that subprocess launches, if you have the know how.
As usual, Python comes through with easy ways to accomplish the tasks thrown at it. I have found very little that Python can’t handle eloquently and in an easy-to-understand way. I hope you find this helpful when you’re starting out and need to know how to open a file or program.