0

The loop is working but once I put the if statements in it only prints I am a dir

If the if statements are not there I am able to print the dirpath, dirname, filename to the console

I am trying to list all the file names in a directory and get the MD5 sum.

from os import walk import hashlib import os path = "/home/Desktop/myfile" for (dirpath, dirname, filename) in walk(path): if os.path.isdir(dirpath): print("I am a dir") if os.path.isfile(dirpath): print(filename, hashlib.md5(open(filename, 'rb').read()).digest()) 

2 Answers 2

1

You're only checking dirpath. What you have as dirname and filename are actually collections of directory names and files under dirpath. Taken from the python docs, and modified slightly, as their example removes the files:

import os for root, dirs, files in os.walk(top): for name in files: print(os.path.join(root, name)) for name in dirs: print(os.path.join(root, name)) 

Will print the list of of directories and files under top and then will recurse down the directories in under top and print the folders and directories there.

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

Comments

1

From the Python documentation about os.walk:

https://docs.python.org/2/library/os.html

dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath.

With os.path.isfile(dirpath) you are checking whether dirpath is a file, which is never the case. Try changing the code to:

full_filename = os.path.join(dirpath, filename) if os.path.isfile(full_filename): print(full_filename, hashlib.md5(open(full_filename, 'rb').read()).digest()) 

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.