Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a file's directory address on a Mac

Tags:

python

macos

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?

like image 419
TopChef Avatar asked Jul 24 '10 09:07

TopChef


People also ask

How do you find a directory address on a Mac?

See the Path Using Finder's Status BarOpen a Finder window, and from the top menu bar, click the “View” button. In the menu that appears, click “Show Path Bar.” Instantly, you will see a new Path Bar at the bottom of every finder window. It will show you the system path to the current folder.

How do I copy a file path on a Mac?

In the Terminal app on your Mac, use the mv command to move files or folders from one location to another on the same computer. The mv command moves the file or folder from its old location and puts it in the new location.


4 Answers

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.

like image 170
Philipp Avatar answered Oct 15 '22 07:10

Philipp


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.

like image 34
Federico klez Culloca Avatar answered Oct 15 '22 06:10

Federico klez Culloca


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)
like image 35
Massimiliano Kraus Avatar answered Oct 15 '22 07:10

Massimiliano Kraus


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.

like image 42
DennisD Avatar answered Oct 15 '22 05:10

DennisD