2014-09-11 121 views
0

我試圖在一系列目錄中創建一個csv的路徑到wav文件。每一行都應該對應一個目錄。一行中的每個單元格都應該包含單個文件的路徑。下面的腳本「幾乎」工作。它創建一個CSV文件作爲單元格。但是,os.path.realpath和os.path.abspath不包含文件的直接父目錄。所以,而不是「/root/directory/file.wav」。我得到「/root/file.wav」。在python中獲取文件的完整路徑

import fnmatch 
import os 
import csv 

with open('filelist.csv', 'wb') as csvfile: 
    lister = csv.writer(csvfile, delimiter=',') 
    for root, dirnames, filenames in os.walk(os.getcwd()): 
     matches = [] 
     for filename in fnmatch.filter(filenames, '*.wav'): 
     matches.append(os.path.realpath(filename)) 
     if len(matches) > 0: 
      print matches 
      lister.writerow(matches) 
+0

作爲一個方面說明,如果你的代碼不是一個沒有縮進的完美樹,那麼你的代碼難以閱讀就會變得更糟。實際上,我認爲您的代碼中實際上可能存在縮進錯誤,但很難確定。你真的想寫第一場比賽,然後是前兩場比賽,然後是前三場比賽,然後是前四場比賽?因爲這就是你的代碼所做的。如果它在'append'後面,'if'語句就毫無意義,因爲它永遠是真的。 – abarnert 2014-09-11 04:09:01

+1

另外,你不需要'os.walk(os.getcwd())',只是'os.walk('。')'很好。而且你不需要'如果len(匹配)> 0:',只是'匹配:'。 (大部分是在PEP 8中。) – abarnert 2014-09-11 04:10:08

回答

1

您需要joinroot路徑從當前目錄得到一個相對路徑,然後你可以打電話abspath *

你可以的例子每一個在看到這對os.walk的文檔,像這樣的:

import os 
for root, dirs, files in os.walk(top, topdown=False): 
    for name in files: 
     os.remove(os.path.join(root, name)) 
    for name in dirs: 
     os.rmdir(os.path.join(root, name)) 

因此,對於您的代碼:

with open('filelist.csv', 'wb') as csvfile: 
    lister = csv.writer(csvfile, delimiter=',') 
    for root, dirnames, filenames in os.walk(os.getcwd()): 
     matches = [] 
     for filename in fnmatch.filter(filenames, '*.wav'): 
      matches.append(os.path.abspath(os.path.join(root, filename))) 
      if len(matches) > 0: 
       print matches 
       lister.writerow(matches) 

*另外,你也可以通過絕對路徑開始walk,而不必abspath每個文件......但只有當你明白這意味着什麼的符號鏈接,並高興。如果您不知道,請在每個文件上使用abspath

+0

是的。是的。那樣做了。出於好奇,如果我只是想要父目錄和文件的輸出(不包括根卷)? – 2014-09-11 04:14:57

+0

@貝利史密斯:我不確定你的意思。你是否正在討論在Windows上刪除驅動器盤符,並以'\'開始而不是'D:\'開始一個絕對驅動器內的路徑?或者在Unix上獲取相對於掛載點的路徑?或者只是一個可用的相對路徑(相對於當前目錄)而不是絕對路徑?要麼 …? – abarnert 2014-09-11 04:28:02

相關問題