Python操作系统模块打印语句

2024-09-27 23:28:11 发布

您现在位置:Python中文网/ 问答频道 /正文

目录内容如下

 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)

Tags: pathtest目录txt内容oscountdir
2条回答

你确定你的打印语句不在for循环中吗?代码格式似乎已关闭,因为for循环和全局变量在functiondef filepath(dir):语句之后没有缩进

您计划在程序中输出什么。您正在递归地调用自己的filepath函数,该函数为每个目录调用自身。在每个函数调用中打印count

我猜您是想打印给定文件夹中的文件数。只需将print(count)语句放在函数定义之外

相关问题 更多 >

    热门问题