首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python os模块打印语句

Python os模块打印语句
EN

Stack Overflow用户
提问于 2018-08-09 06:38:48
回答 2查看 825关注 0票数 0

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)
EN

回答 2

Stack Overflow用户

发布于 2018-08-09 06:47:51

你确定你的print语句没有在for循环中吗?看起来您的代码格式化是关闭的,因为for循环和全局变量在您的函数def filepath(dir):语句后面没有缩进。

票数 1
EN

Stack Overflow用户

发布于 2018-08-14 19:48:49

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

我猜您正在尝试打印给定folder.Just中的文件数,将您的print(count)语句放在函数定义之外。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51756611

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档