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
這解決了我眼前的問題,謝謝。我不確定爲什麼abspath方法返回我的app.py文件的根目錄,而不是posts目錄,儘管 – whatevermike
@ c4binever:我想你認爲'abspath'會「找到一個文件」,但實際上它只是採用你給它的路徑並相對於當前目錄「擴展」它。由於你的當前目錄是'.'而不是'。/ directory',它沒有做你想要的。 –