dir的内容如下
C:\Test\newtext.txt
C:\Test\Test1
C:\Test\Test1\newtext.txt
C:\Test\Test2
count变量将打印三次。为什么它被打印了3次?
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)
发布于 2018-08-09 06:47:51
你确定你的print语句没有在for循环中吗?看起来您的代码格式化是关闭的,因为for循环和全局变量在您的函数def filepath(dir):
语句后面没有缩进。
发布于 2018-08-14 19:48:49
你计划在你的程序中输出什么?您正在递归地调用您自己的filepath
函数,该函数为每个目录调用自身。并且在进行的每个函数调用中都打印出计数。
我猜您正在尝试打印给定folder.Just中的文件数,将您的print(count)
语句放在函数定义之外。
https://stackoverflow.com/questions/51756611
复制相似问题