1

I'm trying to print the file date creation of various files.

So I've tried use this code:

import os
import datetime

pth = r"my_path"

def listDir(dir):
    fileNames = os.listdir(dir)
    for fileName in fileNames:
        t = os.path.getctime(pth + str(\fileName));
        print('Nombre: ' + fileName + t)

listDir(pth)

But, that don't works. Another problem that i have is that i don't know how to put only in the date the "Y/M/D" characters.

I appreciate your help.

1
  • Can you state the error you are getting? Commented Apr 21, 2020 at 6:01

1 Answer 1

1

I see a problem here.

While using .getctime the string you are passing is not a proper file-path. You are concatenating pth with \filename. This syntactically worng.

You are missing the \ or other delimiter used in different os for specifying directories.

You can try the below answer -

import os
import datetime

pth = r"my_path"

def listDir(dir):
    fileNames = os.listdir(dir)
    for fileName in fileNames:
        file_path = os.path.join(pth, fileName)

        ts = os.path.getctime(file_path)        # this returns the creation timestamp.
        dt = datetime.datetime.fromtimestamp(ts)    # this converts the timestamp to datetime object.

        print('Nombre: {0} --> {1}'.format(fileName ,dt.date()))    # dt.date() will return only the date from the datetime object.


listDir(pth)

Notes:

  1. Use os.path.join for concatenating the paths as it takes care of which OS you are using. We don't have to worry about / or \\ or any other delimiter.

  2. Convert the date into datetime object as manipulating and dealing with datetime object will be much more easier than dealing with strings.

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.