2013-05-16 45 views
-4
def cut(path): 
    test = str(foundfiles) 
    newList = [s for s in test if test.endswith('.UnitTests.vbproj')] 
    for m in newList: 
     print m 
    return newList 

這個函數解析foundliles,這是一個文件夾中的文件列表,我已經解析了大約20多個文件。我需要通過「.UnitTests.vbproj」中的每個文件結尾解析這個列表。但是,我無法得到它的工作。任何建議將不勝感激!爲什麼不用這個循環工作

EDIT1:這就是我現在做了我的代碼,我得到的atrribute錯誤消息框,說「元組」對象有沒有屬性「的endsWith」

def cut(path): 
    test = foundfiles 
    newList = [s for s in foundfiles if s.endswith('.UnitTests.vbproj')] 
    for m in newList: 
     print m 
    return newList 
+1

當你說*我無法得到它的工作*,你是什麼意思的工作/不工作? – Maroun

+0

我強烈懷疑foundfiles實際上並不是一個字符串列表,而是一個包含一個字符串的元組列表。當然,如果是這樣的話,''將是一個元組,而不是一個字符串。 – kampu

+0

重複的問題:[此循環應該工作,但它不是](http://stackoverflow.com/q/16587764/214178) – artdanil

回答

2

您打開列表轉換爲字符串。遍歷test給你個人字符,而不是:

>>> foundfiles = ['foo', 'bar'] 
>>> for c in str(foundfiles): 
...  print c 
... 
[ 
' 
f 
o 
o 
' 
, 

' 
b 
a 
r 
' 
] 

沒有必要把foundfiles成字符串。您還需要測試元素列表,不test

newList = [s for s in foundfiles if s.endswith('.UnitTests.vbproj')] 
+0

如果它不是一個字符串我怎麼才能使用.endwith()屬性呢?我以爲你只能在一個字符串的對象上使用它? – BesaseB

+0

@ user2371187:列表中的每個元素*都是一個字符串。這些在列表理解中被逐一分配給's',所以我們測試's.endswith()'。 –

+0

@Martijin我剛剛嘗試過您的修改過的代碼,但它仍然沒有工作(請參閱編輯)是否有可能我錯誤地返回了FoundFiles? – BesaseB

0

我真的不知道什麼是你的「foundfiles」的類型。 也許這樣會幫助你:

def cut(path): 
    import os 
    newlist = [] 
    for parent,dirnames,filenames in os.walk(path): 
     for FileName in filenames: 
      fileName = os.path.join(parent,FileName) 
      if fileName.endswith('.UnitTests.vbproj'):newlist.append(fileName) 
    return newlist