Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python操作系统模块打印语句_Python_Operating System - Fatal编程技术网

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语句中。