Finding a File on your Disk¶
Opening a file requires that you, as a programmer, and Python agree about the location of the file on your disk.
The way that files are located on disk is by their path. You can think of the filename as the short name for a file, and the path as the full name.
For example on a Mac if you save the file hello.txt
in your home directory the path to that file is /Users/yourname/hello.txt
On a Windows machine the path looks a bit different but the same principles are in use. For example on windows the path might be C:\Users\yourname\My Documents\hello.txt
You can access files in folders, also called directories, under your home directory by adding a slash and the name of the folder.
For example, if you had a file called hello.py
in a folder called SI106
that was inside a folder called PyCharmProjects
under your home directory,
then the full name for hello.py
stored in the SI106 folder would be /Users/yourname/PyCharmProjects/SI106/hello.py
Here’s the important rule to remember: If your file and your Python program are in the same directory you can simply use the filename. open('myfile.txt','r')
If your file and your Python program are in different directories then you should use the path to the file open(/Users/joebob01/myfile.txt)
.
Note
For security reasons, our code running in your browser doesn’t read or write files to your computer’s file system. Later in the semester, when you run python
natively on your own computer, you will be able to truly read files, using path names as suggested above. To get you started, we have faked it by providing
a few files that you can read as if they were on your hard disk. In this chapter, we simulate the existence of a textfile called qbdata.txt
. You can’t
open any other files from your local computer from code running this chapter.