2016-08-18 2 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 문을 던지기로 결정했다. 지정된에도 불구하고, 그것은 분 동안 잘 실행 또는 두 개의는 잘 난 그냥 Ctrl 키 Z'd 다시 ipython3에 갔다

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

절을 제외하고 밖으로 뱉어 시작하고 즉시 동일한 메시지를 양육하는, 다시 시도 디렉토리는 /입니다. 왜이 같은 지역에서 다시 시작 되었습니까?

편집 : 코드

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

입니다 : 문자열이 다른 인수로 전달하는 대신 함께 문자열을 추가 할 필요가 ".py"로 끝나는 경우

확인하려면? –

+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이는 indice "py"에서 검사의 시작 "."로 끝나는 경우를 호출하지만 "py" 유효한 indice이 따라서, 아니다 오류. 코드가 어디

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

덕분에 해결되었습니다. – user58641