In part 3 of our series on the Python OS module, we’ll show you how to open files using the Python OS module. Launching files or applications is simple with the Python OS module thanks to built-in system commands.
If you missed it, Part 1 of our series on the Python OS module described how to use chdir and getcwd to set your current working directory. Part 2 demonstrated how to list all files and folders in a directory using Python OS.
Recall that during our series on the Python OS module, we’ll be assuming the following directory structure:
Our first tutorial left off with our current working directory set to
import os os.chdir(r"C:\main directory") wd = os.getcwd()
This will be our starting point for this week’s tutorial on opening files, but we’ll also show examples for how how to open files, regardless of your current working directory.
To open a file using the Python OS module, you need to import the OS module, then call the
system() method and pass it the path of your file. It’s important to recognize that the
system() command doesn’t open a file behind the scenes for reading or writing (file I/O). It physically launches your file or application on your screen using the default program associated with it.
For example, the following script opens the
import os os.system(r"my_wordfile.docx")
Although this script defaults to looking for a file in your current working directory, the
system() method actually lets you specify a full file path. To demonstrate this, run the following Python script, which opens a file and then prints a command letting you know the file was opened:
import os os.system(r"C:\Users\Public\Documents\SampleFile.txt") print("File opened")
The final part of our series on the Python OS module will explain how to create and remove files and folders on your system. Take a look, and then subscribe using the form below for more free tutorials designed to make you a true Python expert.
Want to do more with Python?
We've uncovered a lot more tricks to help you get the most out of Python. To take your Python programming to the next level, enter your email address below and we'll send you our most powerful Python tricks yet.