5

I am writing a short script in python that will scan through a list of folders for image files and then re-organize them.

One of the optional way of organizing them i wish to have is by the date they are created.

Currently, I am trying to read the image creation date as follows

import os.path, time

f = open("hi.jpg")
data = f.read()
f.close()
print "last modified: %s" % time.ctime(os.path.getmtime(f))
print "created: %s" % time.ctime(os.path.getctime(f))

But I get an error that reads

Traceback (most recent call last):
  File "TestEXIFread.py", line 6, in <module>
    print "last modified: %s" % time.ctime(os.path.getmtime(f))
  File "/usr/lib/python2.7/genericpath.py", line 54, in getmtime
    return os.stat(filename).st_mtime
TypeError: coercing to Unicode: need string or buffer, file found

Can anyone tell me what it means?

Nolen Royalty
  • 18,415
  • 4
  • 40
  • 50
davidx1
  • 3,525
  • 9
  • 38
  • 65

1 Answers1

9

You need to be using a string for the filename instead of the file object.

>>> import os.path, time
>>> f = open('test.test')
>>> data = f.read()
>>> f.close()
>>> print "last modified: %s" % time.ctime(os.path.getmtime('test.test'))
last modified: Fri Apr 13 20:39:21 2012
>>> print "created : %s" % time.ctime(os.path.getctime('test.test'))
created : Fri Apr 13 20:39:21 2012
Nolen Royalty
  • 18,415
  • 4
  • 40
  • 50
  • Thank you, the code now works, but could you please explain to me what the difference between the two is? – davidx1 Apr 14 '12 at 01:00
  • 1
    @Synia f is a file object, which is used for reading, writing, or appending to a file. What you need is just the name of the file, not the file itself. – Nolen Royalty Apr 14 '12 at 01:25
  • 2
    attenion: `getctime` will not return the creation-timestamp: https://docs.python.org/2/library/os.path.html#os.path.getctime – anion Oct 30 '19 at 12:46