Reputation: 110173
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.
Upvotes: 4
Views: 16089
Reputation: 37909
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>
Upvotes: 9
Reputation: 15788
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.
Upvotes: 3
Reputation: 56861
with open('c:\absolutepath\file') as f: content = f.read()
Upvotes: 0