Python操作系统模块打印语句
目录的内容如下Python操作系统模块打印语句,python,operating-system,Python,Operating System,目录的内容如下 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): ch
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循环和全局变量在函数
def filepath(dir):
语句之后没有缩进 您计划在程序中输出什么。您正在递归调用自己的filepath
函数,该函数为每个目录调用自身。您正在打印每个函数调用中的计数
我猜您正在尝试打印给定文件夹中的文件数。只需将
print(count)
语句置于函数定义之外。我已更正缩进。以下是输出:['New Text Document.txt'、'Test1'、'Test2']C:\Test\New Text Document.txt C:\Test\Test1\New Text Document.txt 2您正在filepath()函数中调用filepath()函数,因此每次调用该函数时都会打印计数。嵌套调用位于if语句中。