David542
David542

Reputation: 110173

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.

Upvotes: 4

Views: 16089

Answers (4)

samplebias
samplebias

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

Blair
Blair

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

Senthil Kumaran
Senthil Kumaran

Reputation: 56861

  1. Use absolute path to the file, because if you move your program to another location or another computer, relative paths will break.
  2. Use context manager while opening the file.
with open('c:\absolutepath\file') as f:
   content = f.read()

Upvotes: 0

manojlds
manojlds

Reputation: 301147

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

Upvotes: 0

Related Questions