1

I'm writing a code in Python to list all files with their sizes and date of creation in a specific directory including its sub-directories. The code I ended up with works only for the current directory, but not for a specific directory. If I replace the value of the variable folder by a specific directory it comes up with an error.

Below is my code:

import os, sys, time

folder = "C:\ENTD261"
listOfFiles = ""
for root, dirs, files in os.walk(folder):
      for list in files:
       file_size = os.path.getsize(list)
       createDate = time.ctime(os.path.getctime(list))
       listOfFiles = list, "Size: %.1f bytes"%file_size, "Created date: " + createDate
       print(listOfFiles)
1
  • Did you read the error? Commented Jul 4, 2019 at 19:49

1 Answer 1

1

For specific directory, you need to join the root path with the file path for full path.

for root, dirs, files in os.walk(folder):
for list in files:
    list=os.path.join(root,list) # joining root and the file name for full path
    file_size = os.path.getsize(list)
    createDate = time.ctime(os.path.getctime(list))
    listOfFiles = list, "Size: %.1f bytes"%file_size, "Created date: " + createDate
    print(listOfFiles)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, Ricky Kim you're a lifesaver. I definitely learned from your code.

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.