2016-12-24 104 views
0

我試圖遍歷目錄中的文件並列出每個目錄的路徑。 我的代碼遍歷每個文件,但列出了錯誤的目錄。我錯過了什麼來返回完整的目錄?Python循環遍歷目錄中的文件然後列出

這裏是我到目前爲止的代碼:

import os 

directory = "posts/" 

for file in os.listdir(directory): 
    if file.endswith(".md"): 
     dir = os.path.abspath(file) 
     print "The Path is: " + str(dir) 

的結構是這樣的:

從終端(缺少目錄的 /posts/部分)
. 
├── app.py 
└── posts 
    ├── first.md 
    └── second.md 

輸出:

The Path is: /home/tc/user/python-md-reader/second.md 
The Path is: /home/tc/user/python-md-reader/first.md 

回答

1

您可以將目錄放回路徑中:

dir = os.path.abspath(os.path.join(directory, file)) 
+0

這解決了我眼前的問題,謝謝。我不確定爲什麼abspath方法返回我的app.py文件的根目錄,而不是posts目錄,儘管 – whatevermike

+1

@ c4binever:我想你認爲'abspath'會「找到一個文件」,但實際上它只是採用你給它的路徑並相對於當前目錄「擴展」它。由於你的當前目錄是'.'而不是'。/ directory',它沒有做你想要的。 –

3

如果你看看源代碼:

def abspath(path): 
    """Return the absolute version of a path.""" 
    if not isabs(path): 
     if isinstance(path, unicode): 
      cwd = os.getcwdu() 
     else: 
      cwd = os.getcwd() 
     path = join(cwd, path) 
    return normpath(path)   # normpath according to the comment 
            # """Normalize path, eliminating double slashes, etc.""" 

什麼abspath確實是簡單地加入與您提供的path當前工作目錄,因爲你只提供文件的路徑,你是posts目錄中的一個級別,它將被忽略。