我有一个递归调用的函数,我想知道当前的递归级别。下面的代码显示了我用来计算它的方法,但是没有给出预期的结果。
例如。 :要查找系统路径的递归级别:
import os
funccount = 0
def reccount(src):
global funccount
print "Function level of %s is %d" %(src, funccount)
def runrec(src):
global funccount
funccount = funccount + 1
lists = os.listdir(src)
if((len(lists) == 0)):
funccount = funccount - 1
reccount(src)
for x in lists:
srcname = os.path.join(src, x)
if((len(lists) - 1) == lists.index(x)):
if (not(os.path.isdir(srcname))):
funccount = funccount - 1
if os.path.isdir(srcname):
runrec(srcname)
runrec(C:\test)
问题:给定目录路径,打印目录的递归级别
目录结构是:
在我的目录结构中,我将调用函数“ reccount(Test)”(该函数将使用MainFolder的路径来调用)。我想知道每个文件夹的递归调用级别。 (仅限目录)
Test:
|----------doc
|----------share
|----------doc
|----------file1
|----------bin
|----------common
|----------doc
|----------extras
|----------file2
当我调用该过程时,得到以下结果:
Function level of C:\test is 1
Function level of C:\test\bin is 2
Function level of C:\test\bin\common is 3
Function level of C:\test\bin\common\doc is 3
Function level of C:\test\doc is 3
Function level of C:\test\extras is 3
Function level of C:\test\share is 4
Function level of C:\test\share\doc is 5
如您所见,当它打印bin / common / doc的结果时,它将打印3而不是4,并且所有后续结果都是错误的
python大神给出的解决方案
def some_method(data, level=0):
some_method(..., level=level+1)
if __name__ == '__main__':
some_method(my_data)
Python sqlite3数据库已锁定 - python我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…
Python pytz时区函数返回的时区为9分钟 - python由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
如何打印浮点数的全精度[Python] - python我编写了以下函数,其中传递了x,y的值:def check(x, y): print(type(x)) print(type(y)) print(x) print(y) if x == y: print "Yes" 现在当我打电话check(1.00000000000000001, 1.0000000000000002)它正在打印:<…
Python:检查新文件是否在文件夹中[重复] - pythonThis question already has answers here: How do I watch a file for changes? (23个答案) 3年前关闭。 我是python的新手,但是我尝试创建一个自动化过程,其中我的代码将侦听目录中的新文件条目。例如,某人可以手动将zip文件复制到一个特定的文件夹中,并且我希望我的代码能够在文件完全…