0

I am working on a code that must obtain the directory from the user and produce the following output of each file: Path, FileName, FileSize, and Last Modified Date, and md5 hash.

Here is my code so far:

import os, sys
import stat
import os.path, time
import hashlib

newDirectory = raw_input("Please select a directory to search: ")


while not os.path.exists(newDirectory):
    print "Invaid Directory"
    newDirectory = raw_input("Please select a directory to search: ")
print "Valid Directory"

dirList = os.listdir(newDirectory)

for file in dirList:
    print '\n'
    print os.path.abspath(file)
    print file
    print os.path.getsize(file)

So my output without "print os.path.getsize(file)" prints the path and file name of all the files in the folder. As soon as I add "print os.path.getsize(file)" I get the error message below:

File "C:\Python27\Lib\genericpath.py", line 57, in getsize return os.stat(filename).st_size

WindowsError: [Error 2] The system cannot find the file specified: 'filename'

Clearly, the file exists since it pulls the path and file name. Not sure what I am doing wrong.

  • try `os.path.getsize(os.path.join(newDirectory,file))` – Jean-François Fabre Dec 17 '17 at 20:09
  • You are printing the `abspath` to each file; does that match where the file actually is? – Scott Hunter Dec 17 '17 at 20:09
  • @ScottHunter unless `newDirectory` is the current dir, it just cannot. – Jean-François Fabre Dec 17 '17 at 20:11
  • @Jean-FrançoisFabre which would explain why the code doesn’t work – Scott Hunter Dec 18 '17 at 00:26
  • @Jean-FrançoisFabre thank you for your response. That seemed to work just fine. Also, apologies for the duplicate question. I do have one last question: If i needed to modify my code to add a sorting feature that would sort all the file information by file size, how would I do that? I feel like I would need to pass the information through a list or array prior to sorting, but I'm not sure how to begin. – Alison Coakley Dec 18 '17 at 02:19
  • https://stackoverflow.com/questions/168409/how-do-you-get-a-directory-listing-sorted-by-creation-date-in-python, then change os.path.getmtime by os.path.getsize – Jean-François Fabre Dec 18 '17 at 06:29

0 Answers0