2016-08-18 74 views
0

我正在製作一個遞歸搜索具有特定後綴的文件目錄的函數。python3中的遞歸文件搜索問題

TypeError: slice indices must be integers or None or have an index method

指着這一行:

if path.endswith('.',sf)==True: l.append(path)

.endswith()返回一個布爾值,用來測試串,憑啥是它給了我關於非整數的問題?

此外,我決定只打印所有內容,如果文件不是目錄或文件(導致第一次運行很快發生),則只需輸出try/except語句。它跑罰款一兩分鐘,然後開始吐出except子句

something went wrong with /sys/bus/cpu/devices/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu1/node0/cpu0/node0/cpu1/subsystem/devices/cpu0/node0/cpu0/subsystem/devices/cpu0/subsystem/devices/cpu0/subsystem something went wrong with /sys/bus/cpu/devices/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu1/node0/cpu0/node0/cpu1/subsystem/devices/cpu0/node0/cpu0/subsystem/devices/cpu0/subsystem/devices/cpu0 something went wrong with /sys/bus/cpu/devices/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu0/node0/cpu1/node0/cpu0/node0/cpu1/subsystem/devices/cpu0/node0/cpu0/subsystem/devices/cpu0/subsystem/devices/cpu1/cache/power

以及我只是按Ctrl-Z'd回到了ipython3了一次又一次,這立即提出了同樣的消息,即使指定目錄是/。爲什麼它從這個相同的區域開始回來?

編輯:代碼

def recursive_search(dr, sf): 
    """searches every potential path from parent directory for files  with  the matching suffix""" 
    l=[]#for all the good little scripts and files with the right last name 
    for name in os.listdir(dr):#for every item in directory 
path=os.path.join(dr, name)#path is now path/to/item 

if os.path.isfile(path): 
    if path.endswith('.',sf)==True: 
    l.append(path) 
else: 
    #try: 
    recursive_search(path, sf) 
    #except: 
    #print ('something went wrong with ', path) 

,如果它找出來怪異,我遇到一些麻煩的格式。

+1

這裏是你的代碼? –

+2

我猜'endswith'的'sf'參數既不是整數,也不是None,正如在回溯中提到的那樣。請顯示您使用的代碼。 – Frodon

+0

即使它不在代碼中,我通過從根開始並搜索python腳本來測試它:recursive_search('/','py') – user58641

回答

0

看看文檔爲str.endswith

>>> help(str.endswith) 
Help on method_descriptor: 

endswith(...) 
    S.endswith(suffix[, start[, end]]) -> bool 

    Return True if S ends with the specified suffix, False otherwise. 
    With optional start, test S beginning at that position. 
    With optional end, stop comparing S at that position. 
    suffix can also be a tuple of strings to try. 

所以調用"path".endswith('.',"py")檢查字符串path如果它與"."開始是從指數之"py"檢查結束,但是"py"是不是一個有效的指數之,因此,錯誤。

要檢查字符串需要字符串相加而不是把它當作另一種說法".py"結束:

path.endswith("."+sf) 
+0

謝謝,解決了它。 – user58641