19

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?

TopChef
  • 43,745
  • 10
  • 28
  • 27

4 Answers4

20

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
  • 48,066
  • 12
  • 84
  • 109
  • _"If you want this to be portable across operating systems"_ ... you have also to correct the path separators, for example from '/' to '\' if you go to Windows. See my answer. – Massimiliano Kraus Nov 22 '16 at 11:44
12
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.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • “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 Jul 24 '10 at 09:12
  • 1
    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 Jul 24 '10 at 09:17
  • corrected, but now my answer is almost identical to yours :-( – Federico klez Culloca Jul 24 '10 at 09:33
2

You're working on a Mac so paths like "a/b/c.text" are fine, but if you use Windows in the future, you'll have to change all the '/' to '\'. If you want to be more portable and platform-agnostic from the beginning, you better use the os.path.join operator:

import os

desktop = os.path.join(os.path.expanduser("~"), "Desktop")
filePath = os.path.join(desktop, "somefile.txt")

f = open(filePath)
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
1

If this is still an issue, I had the same problem and called Apple. I learned that the file I'd created was saved on iCloud. The Apple guy told me to save the file locally. I did that and the problem was solved.

DennisD
  • 21
  • 2