0

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)

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have corrected the indentation.Below is the output: ['New Text Document.txt', 'Test1', 'Test2'] C:\Test\New Text Document.txt C:\Test\Test1\New Text Document.txt 2 2 2
You are calling your filepath() function inside of the filepath() function, so the count gets printed every time the function gets called. The nested call is in your if statement.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.