Q:

Open file in Python

My cwd is ~/Desktop/Development/Python/djcode/mysite, and I want to open a file on my Desktop. What is the syntax to open files in a different directory? (for example, if the file was in the cwd I would use open('file'). Thank you.

A:

Try this:
>>> import os
>>> path = os.path.expanduser('~/Desktop/foo.txt')
>>> open(path, 'r')
<open file '/home/pat/Desktop/foo.txt', mode 'r' at 0x7f0455af0db0>

A:

Use the path to it, either absolute:
myfile = open('/path/to/myfile.ext')

or relative:
myfile = open('../../../../myfile.ext')

depending on which is more appropriate for the situation. You can use os.path.expanduser() to expand the ~ portion of the path.

A:

Use relative paths? ../../../../file

