Isak
Isak

Reputation: 545

Writing a list of creation time of items in a folder

I'm trying to write a text file with the creation date of each file in a directory. I had a look at this question, but I'm still in need of help, besides being curious about why the code below doesn't work.

I think I'm close. It kind of works with the creation date of the folder, but I want to know when the files were created.

import os, os.path, time, datetime    
mydir = '/home/user/ebay/'
mydir2 = '/home/user/'
def writefiles():
    with open(mydir2 + '/items.txt', "wb") as a:
        for path, subdirs, files in os.walk(mydir):
            for file in files:
                a.write(file+' , '+(time.ctime(os.path.getctime(file))) + os.linesep)
writefiles()

I get this error message:

OSError: [Errno 2] No such file or directory: 'PkV20ZrzMs'

This is odd, because there is a file called 'PkV20ZrzMs'. I tried to add the directory location but it didn't make any difference.

The reason I think I'm close is that when I change (os.path.getctime(file) to (os.path.getctime(path) I get the creation date of the folder, like this:

PkV20ZrzMs , Fri Mar 20 13:43:31 2015
qZzo0ZUAtm , Fri Mar 20 13:43:31 2015
Tm5f8Lhgcd , Fri Mar 20 13:43:31 2015
vgMCBGdJu0 , Fri Mar 20 13:43:31 2015
Ja7Bwa5uEi , Fri Mar 20 13:43:31 2015

Upvotes: 0

Views: 167

Answers (1)

xnx
xnx

Reputation: 25508

The following works for me, so perhaps there's something up with your path? Note that you have a trailing slash in your mydir2 that might mess up the path you're writing to when you concatenate '/items.txt'.

import os, os.path, time, datetime    

mydir = '/home/xnx/temp'
mydir2 = '/tmp'

def writefiles():
    with open(mydir2 + '/items.txt', "wb") as a:
        for path, subdirs, files in os.walk(mydir):
            for file in files:
                a.write(file+' , '+(time.ctime(os.path.getctime(
                           os.path.join(path, file)))) + os.linesep)
writefiles()

Upvotes: 1

Related Questions