1

I want the output to be in the form:

dic = {size1:file/path1, size2:file/path2}

But what I am getting in individual dictionaries for each combination, like:

{size1:file/path1}
{size2:file/path2, size1:file/path1, ...}

This is the code I came up with, can anyone correct my code.

import os, subprocess, re, sys
records = {}
out = sys.stdout
with open('PythonFilesInMac.txt', 'w') as outfile:
     sys.stdout = outfile
     for cdir, dir, files in os.walk(r'/Users'):
         for file in files:
             if file.endswith('.py'):
                filename = os.path.join(cdir, file)
                size = os.path.getsize(filename)
                records[size] = filename #records = {size:filename}
                print records             #how do I use dict.update() here?   
     sys.stdout = out
5
  • 1
    You are getting all of the combinations because you are printing out records in every loop. Commented May 17, 2015 at 5:23
  • 1
    You can print after loop end. Commented May 17, 2015 at 5:25
  • 1
    your code seems correct, do a print records after your loop to check that it is indeed correct Commented May 17, 2015 at 5:26
  • 1
    what will result when size of two or more files are same ? Commented May 17, 2015 at 5:27
  • 1
    if two files have the same size, this code will silently overwrite the first. Commented May 17, 2015 at 5:30

1 Answer 1

1

there are two problems in your code. the first is you should put print outside your loop. the second is there may be two files with same size, better to put them in a list.

import os, subprocess, re, sys
records = {}
out = sys.stdout
with open('PythonFilesInMac.txt', 'w') as outfile:
     sys.stdout = outfile
     for cdir, dir, files in os.walk(r'/Users'):
         for file in files:
             if file.endswith('.py'):
                filename = os.path.join(cdir, file)
                size = os.path.getsize(filename)
                records.setdefault(size, []).append(filename)
     print records  
     sys.stdout = out
Sign up to request clarification or add additional context in comments.

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.