簡體   English   中英

如何在用戶輸入的子目錄中訪問文件而不必在Python 2.7.11中聲明目錄?

[英]How do I access a file in a sub-directory on user input without having to state the directory in Python 2.7.11?

我有一個依賴用戶輸入的程序,可以輸入要在Python 2.7.11中打開的程序文件。 我在原始目錄Detector一個名為TestCases的子目錄中擁有所有這些文件,但是當從超級目錄運行該程序時,我似乎無法訪問TestCases的文件。 我試圖使用os.path.join但無濟於事。 這是我的代碼:

import os.path
def __init__(self):
    self.file = None
    os.path.join('Detector', 'TestCases')

    while self.file == None:
        self.input = raw_input('What file to open? ')
        try:
            self.file = open(self.input, 'r')
        except:
            print "Can't find file."

運行程序時,我的終端如下:

>>> What file to open? test.txt # From the TestCases directory
>>> Can't find file.
>>> What file to open? ...

我使用os.path.join不正確嗎? 我認為應該鏈接兩個目錄,以便在從超級目錄運行程序時可以從子目錄訪問文件。

有關os.path.join的文檔

智能地連接一個或多個路徑組件。 返回值是路徑的串聯。

您似乎希望它設置某種PATH變量或影響當前的工作目錄。 首先,將這樣的代碼添加到代碼中就足夠了:

open(os.path.join("TestCases",self.input), 'r')

您正在使用os.path.join('Detector','TestCases'),它應該返回'Detector / TestCases',但您並未在任何地方存儲該變量。

我想您位於Detector目錄中,並且想要在TestCases中打開文件。 在這種情況下,您可以使用路徑聯接(它連接其參數並返回結果):

    import os.path

    file = None
    while not file:
        input = raw_input('What file to open? ')
        try:
            filepath = os.path.join('TestCases', input)
            file = open(filepath, 'r')
        except IOError:
            print "Can't find " + input

我已經存儲了os.path.join的結果,所以您可以看到它不會更改目錄,它只是連接了其參數,也許您以為函數會更改目錄,您可以使用os.chdir來完成。

首先在簡單的腳本中或在終端中嘗試它,它將省去很多麻煩。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM