Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file in Python

Tags:

python

django

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.

like image 415
David542 Avatar asked Dec 16 '22 14:12

David542


2 Answers

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>
like image 138
samplebias Avatar answered Dec 28 '22 03:12

samplebias


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.

like image 30
Blair Avatar answered Dec 28 '22 03:12

Blair