目录内容如下
C:\Test\newtext.txt
C:\Test\Test1
C:\Test\Test1\newtext.txt
C:\Test\Test2
count变量被打印了三次。为什么要印 三次
import os
dir = 'C:\\Test'
print(os.listdir(dir))
count = 0
def filepath(dir):
global count
for path in os.listdir(dir):
childPath = os.path.join(dir,path)
if os.path.isdir(childPath):
filepath(childPath)
else:
count += 1
print(childPath)
print(count)
filepath(dir)
你确定你的打印语句不在for循环中吗?代码格式似乎已关闭,因为for循环和全局变量在function
def filepath(dir):
语句之后没有缩进您计划在程序中输出什么。您正在递归地调用自己的
filepath
函数,该函数为每个目录调用自身。在每个函数调用中打印count我猜您是想打印给定文件夹中的文件数。只需将
print(count)
语句放在函数定义之外相关问题 更多 >
编程相关推荐