retro_var
retro_var

Reputation: 145

How i can print the file creation date of various files in Python?

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.

Upvotes: 1

Views: 175

Answers (1)

Prashant Kumar
Prashant Kumar

Reputation: 2092

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.

Upvotes: 1

Related Questions