2011-04-30 95 views
4

我的cwd是〜/ Desktop/Development/Python/djcode/mysite,我想在我的桌面上打開一個文件。在其他目錄中打開文件的語法是什麼? (例如,如果該文件是在CWD我會使用open( '文件')謝謝在Python中打開文件

+1

你嘗試過什麼?請發佈你正在使用的代碼和錯誤信息。 – 2011-04-30 00:59:41

回答

0

使用相對路徑../../../../file

+0

對,謝謝。我正在嘗試到達主目錄,但我想它在Python解釋器中不能識別。 – David542 2011-04-30 01:10:07

+0

@ David542:錯誤。請發佈代碼和錯誤消息。 – 2011-04-30 01:22:46

9

試試這個:。。?

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

使用路徑到它,無論是絕對的:

myfile = open('/path/to/myfile.ext') 

或相對:

myfile = open('../../../../myfile.ext') 

取決於哪種情況更適合。您可以使用os.path.expanduser()來擴展路徑的~部分。

0
  1. 使用該文件的絕對路徑,因爲如果將程序移動到另一個位置或另一臺計算機,相對路徑將中斷。
  2. 打開文件時使用上下文管理器。
with open('c:\absolutepath\file') as f: 
    content = f.read()