tags:

views:

34

answers:

2

I am working with a Macbook programming python. What I want to know is how I can access certain files using Python's file functions. A google search failed me.

For example, Windows would be something like this:

f = open(r'C:\text\somefile.txt')

How would I access something from a folder saved on the Desktop of a Mac?

+2  A: 
f = open (r"/Users/USERNAME/Desktop/somedir/somefile.txt")

or even better

import os
f = open (os.path.expanduser("~/Desktop/somedir/somefile.txt"))

Because on bash (the default shell on Mac Os X) ~/ represents the user's home directory.

klez
“Because on *nix systems `~/` represents the user's home directory.”—This is wrong, it's only a convention used by popular shells such as bash. Trying to open `~/somefile.txt` will look for a directory called `~` inside the current directory.
Philipp
corrected, thanks
klez
@klez: It's not corrected—`open` never expands `~`, and it never uses a shell. Try `open("~/somefile.txt", "w")`—it will fail to create the file unless you have a directory named `~`.
Philipp
corrected, but now my answer is almost identical to yours :-(
klez
+3  A: 

The desktop is just a subdirectory of the user’s home directory. Because the latter is not fixed, use something like os.path.expanduser to keep the code generic. For example, to read a file called somefile.txt that resides on the desktop, use

import os
f = open(os.path.expanduser("~/Desktop/somefile.txt"))

If you want this to be portable across operating systems, you have to find out where the desktop directory is located on each system separately.

Philipp