0

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

21
  • 2
    You are missing a quotation mark (') on line 1 Commented Mar 11, 2021 at 17:13
  • i think that happened while copying the code from IDE @QWERTYL Commented Mar 11, 2021 at 17:15
  • Are you sure the path has greater than 0 files and the path is not changing? Commented Mar 11, 2021 at 17:16
  • filepath changes according to files inside Logs_of_Hell @YeshwinVermaTheProgrammer Commented Mar 11, 2021 at 17:19
  • Please show us your complete output. It should not be possible from the code you show us for the first and second calls to print to print different things, because you don't change any value inside user between the two calls. After the second call, you might be changing the value in code you aren't showing us. Commented Mar 11, 2021 at 17:20

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

7 Comments

So what if i wanted to return the value of user to someother function ,where i can combine user with another dictionaries . that was the reason why i wanted to print user inside "for name in subdirs:" , so that i can directly combine . since i didn't complete the programming of second dictionary , and it is of no use if i don't get user printed
Do you want an array of dictionaries? Or a one big dict indexed by the path?
I updated the code , with merging , so i wanted to merge this user with "nextone" , for doing that i want the user dict to be visible inside that for loop
@AuroraEugene mrgDict .update(nextone) , but that is just going to overwrite the entries in mrgDict with nextone. Exactly what output are you expecting? It's not clear what you want your program to output. Please give an example.
i guess u understood what i wanted in user dict , it is same as u are thinking , i want the foldername and filecount on user dict . secondly , i wanted to merge this "user" with "nextone" which is another dictionary with common key "filepath" and extra key modified dates of new and old file inside a folder , so that i can get a new dict with foldername , count , oldmodified date and new modified date
|
0

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.