2016-08-18 16 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文をスローすることにしました。それが2分の罰金走った後、よく私は、指定されたにも関わらず、すぐに同じメッセージを育てた、ちょうど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

私はrootで始まって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. 

だから、それはindice "py"からチェックの開始"."で終わる場合、しかし"py"が故に、有効indiceない文字列path"path".endswith('.',"py")チェックを呼び出しますエラー。あなたのコードはどこに

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

ありがとう、それが解決しました。 – user58641

関連する問題