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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With