Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping a forward slash path directory in Mac OSX using Python?

This is my second post, I apologize if I do something incorrectly - I will try to be as concise as possible.

I did some searching, and most escapes have to deal with embedded JSON strings - my problem is actually with opening the file itself.

At present, I'm trying to make my code as generic as possible, so I'm using:

file = open(os.path.expanduser(r'~/Desktop/Austin/Tweets/10_7_2012_12/09-Tweets.txt'), 'r')

The issue is that when the interpreter sees this code, it sees the "/" in the file name, and I think it's trying to go down another directory. I confirmed this by removing the "/" in the file name and typing:

file = open(os.path.expanduser(r'~/Desktop/Austin/Tweets/10_7_2012_1209-Tweets.txt'), 'r')

And it loaded just fine.

The problem with doing that for all of these files is that I have several hundred files containing several thousand tweets, and it's a little impractical.

So my question is this: Is there a way in which to load files with forward slashes in their file name?

I saw many ways to load files with the search button, but none including how to deal with a forward slash in the name... I've tried:

file = open(os.path.expanduser('~/Desktop/Austin/Tweets/10_7_2012_12\/09-Tweets.txt'), 'r')

and

file = open(os.path.expanduser('~/Desktop/Austin/Tweets/10_7_2012_12//09-Tweets.txt'), 'r')

All to no avail.

An explanation as to how Python handles forward slashes would be welcome, if anyone cares to teach a naive undergraduate.

I'm using a Mac OSX on Leopard. I'm running a web crawler that's communicating with the Twitter Streaming API; the slashes in the names are a result of saving them with a "/" to designate the date.

SOLUTION: You can use forward slashes in filenames on Mac OSX. From the filesystem's perspective, the / is actually a colon, and it gets translated to a / in Finder.

Kindall's explanation below: It's necessary for the Carbon layer, which uses the standard Mac filename separators, colons. Slashes have historically been allowed in Mac filenames going back to 1984. Mac users also expect to see colons, not slashes, as pathname separators in the GUI (or at least they did in 2001, when this behavior was instituted).

like image 908
Noc Avatar asked Jul 10 '12 17:07

Noc


2 Answers

I'm assuming you're using a Unix-like OS, and my understanding is that forward slashes aren't allowed in filenames in such systems. What do you see if you ls in ~/Desktop/Austin/Tweets/?

like image 154
Russell Borogove Avatar answered Nov 14 '22 05:11

Russell Borogove


Personally I'd rather run a batch rename tool on those files. Slash in a file name is generally a bad idea.

Otherwise, the answer is r'~/Desktop/Austin/Tweets/10_7_2012_12:09-Tweets.txt'. cf. Special characters in OSX filename ? (Python os.rename)

like image 2
Qnan Avatar answered Nov 14 '22 05:11

Qnan