human01302015
human01302015

Reputation: 1

Python os module print statement

Contents of the dir as below

 C:\Test\newtext.txt
 C:\Test\Test1
 C:\Test\Test1\newtext.txt
 C:\Test\Test2

The count variable is getting printed three times. Why is it getting printed 3 times?

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)

Upvotes: 0

Views: 2153

Answers (2)

Naseer Mohammad
Naseer Mohammad

Reputation: 431

What are you planning to output in your program. You are recursively calling your own filepath function which is calling itself for each directory. And you're printing count in each function call being made.

I guess you are trying to print the number of files in the given folder.Just put your print(count) statement outside of the function definition.

Upvotes: 0

Mason Caiby
Mason Caiby

Reputation: 1924

Are you sure your print statement isn't inside your for loop? It looks like your code formatting is off, since the for loop and global variables aren't indented after your function def filepath(dir): statement.

Upvotes: 1

Related Questions