Aurora Eugene
Aurora Eugene

Reputation: 75

Count returns zero when placed inside a loop Using PYTHON

I have written a code that should display the folder name and file count inside the folder. The code works fine when keeping outside a loop but returns me count as zero when I keep the code inside the loop

root = 'C:/Users/PycharmProjects/Logs_of_Hell'
count_of_file = 0

import pathlib
noOfFiles = local_time_of_oldest = local_time_of_newest= 0
subdir=""
N = 0

def get():
    for path, subdirs, files in os.walk(root):
        N_c = len(files)
        user = {}
        user['filepath'] = path
        user['count'] = N_c

        print("Printing first User")
        print(user) # prints  {'filepath': 'C:/Users/PycharmProjects/Logs_of_Hell\\results\\0', 'count': 3}

        print("second")
        for name in subdirs:
            print(user)# prints  {'filepath': 'C:/Users/PycharmProjects/Logs_of_Hell\\results\\0', 'count': 0}
            #.....

so here it works fine and gives me the correct count on the first print and gives me zero counts on the second. am able to retrieve the file path, but the value of count turns to zero. I tried debugging giving a static value that works fine on both prints, but when I try using it like this, the count value turns zero on the second print. Can anyone explain to me why am not able to get the count value on the second loop

this is output am observing , even though i use the same dict variable na , the value is different for both prints :

{'filepath': 'C:/Users/Logs_of_Hell\\pabot_results', 'count': 0}
second
{'filepath': 'C:/Users/Logs_of_Hell\\pabot_results', 'count': 0}
second

Printing first User
{'filepath': 'C:/Users/Logs_of_Hell\\pabot_results\\0', 'count': 3}
Printing first User
{'filepath': 'C:/Users/Logs_of_Hell\\pabot_results\\1', 'count': 3}

Process finished with exit code 0

Tried Editing Code :

import os
import time
import glob
root = 'C:/Users/PycharmProjects/Logs_of_Hell'
count_of_file = 0

import pathlib
noOfFiles = local_time_of_oldest = local_time_of_newest= 0
subdir=""
N = 0
nextone ={}

def get():
    for path, subdirs, files in os.walk(root):
        N_c = len(files)
        user = {}
        user['filepath'] = path
        user['count'] = N_c
        # print(N_c)
        print(user)

        for name in subdirs:
            print(user)
            # # print(os.path.join(path, name))
            subdir = os.path.join(path, name)
            if(os.path.isdir(subdir)):
                taggedrootdir = pathlib.Path(subdir)
                oldest_file = (min([f for f in taggedrootdir.resolve().glob('**/*') if f.is_file()], key=os.path.getmtime))
                newest_file = (max([f for f in taggedrootdir.resolve().glob('**/*') if f.is_file()], key=os.path.getmtime))

                c_time_of_oldest = os.path.getctime(oldest_file)
                local_time_of_oldest = time.ctime(c_time_of_oldest)

                c_time_of_newest = os.path.getctime(newest_file)
                local_time_of_newest = time.ctime(c_time_of_newest)
                nextone['filepath'] = subdir
                nextone['newest'] = local_time_of_newest
                nextone['oldest'] = local_time_of_oldest
                # print(nextone)
                mrgDict = mergeDict(user, nextone) # performing merging 

but the second print only prints the last value

Upvotes: 0

Views: 165

Answers (2)

Aurora Eugene
Aurora Eugene

Reputation: 75

Actually that was quite simple code , i think i confused my self with lot of requirements . So what i did was instead of using multiple loops i used single loop and pushed it to a dictionary .

Upvotes: 0

shrewmouse
shrewmouse

Reputation: 6030

I suspect that you meant to make get a recursive function.

import os

root = './Logs'
count_of_file = 0

import pathlib
noOfFiles = local_time_of_oldest = local_time_of_newest= 0
subdir=""
N = 0

def get(root):
    for path, subdirs, files in os.walk(root):
        N_c = len(files)
        user = {}
        user['filepath'] = path
        user['count'] = N_c

        print("Printing first User")
        print(user) # prints  {'filepath': 'C:/Users/PycharmProjects/Logs_of_Hell\\results\\0', 'count': 3}

        print("second")
        for name in subdirs:
            get(name)

get(root)
~

What output do you expect from the following directory structure?

[root@sri-0000-0001 sandbox]# tree Logs/
Logs/
├── 0
│   ├── log1
│   ├── log2
│   └── log3
└── 1
    ├── log1
    ├── log2
    └── log3

2 directories, 6 files

Output:

[root@sri-0000-0001 sandbox]# python test.py
Printing first User
{'count': 0, 'filepath': './Logs'}
second
Printing first User
{'count': 3, 'filepath': './Logs/1'}
second
Printing first User
{'count': 3, 'filepath': './Logs/0'}
second

If you are trying to stuff info all into the same dict then you need to modify the same dict every time through the recursion.

import os

root = './Logs'
count_of_file = 0

import pathlib
noOfFiles = local_time_of_oldest = local_time_of_newest= 0
subdir=""
N = 0


counts={}

def get(root):
    for path, subdirs, files in os.walk(root):
        N_c = len(files)
        user = {}
        counts[path]={}
        counts[path]['count']=N_c
        #user['filepath'] = path
        #user['count'] = N_c

        #print("Printing first User")
        #print(user) # prints  {'filepath': 'C:/Users/PycharmProjects/Logs_of_Hell\\results\\0', 'count': 3}

        for name in subdirs:
            get(name)

get(root)

print(counts)

Which would give you:

[root@sri-0000-0001 sandbox]# python test.py
{'./Logs/1': {'count': 3}, './Logs/0': {'count': 3}, './Logs': {'count': 0}}

Not using a global:

import os

root = './Logs'
count_of_file = 0

import pathlib
noOfFiles = local_time_of_oldest = local_time_of_newest= 0
subdir=""
N = 0



def get(root):
    counts={}
    for path, subdirs, files in os.walk(root):
        N_c = len(files)
        user = {}
        counts[path]={}
        counts[path]['count']=N_c
        #user['filepath'] = path
        #user['count'] = N_c

        #print("Printing first User")
        #print(user) # prints  {'filepath': 'C:/Users/PycharmProjects/Logs_of_Hell\\results\\0', 'count': 3}

        for name in subdirs:
            counts.update(get(name))

    return counts

counts=get(root)

print(counts)

Upvotes: 1

Related Questions