python3 中的递归文件搜索问题

issue with recursive file search in python3

我正在制作一个函数,该函数以递归方式在目录中搜索具有特定后缀的文件。

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

指向这一行:

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

.endswith() returns 一个布尔值,用于测试字符串,为什么它给我关于非整数的问题?

我还决定只打印所有内容并在文件不是目录或文件时放入 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 回到 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)

如果它看起来很奇怪,我在格式化时遇到了一些问题。

查看 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)