4

First question. I am new to programming, much less python. As the title says I am attempting to find files that were created or modified in the past 24 hours, then move those files to another directory. I can find the files but I can't figure out how to move the files that meet this criteria. My script so far:


for root,dirs,files in os.walk('source\folder'):
for file_name in files: now = dt.datetime.now() before = now - dt.timedelta(hours=24) path = os.path.join(root,file_name) st = os.stat(path)
mod_time = dt.datetime.fromtimestamp(st.st_ctime) if mod_time < before: print('%s modified %s'%(path,mod_time))

I've attempted to use shutil to move the output but I get an error;

TypeError: coercing to Unicode: need string or buffer, datetime.datetime found

I've tried to find a solution online but haven't had any luck. Not even sure if I can do what I am trying to do with the way I have this constructed? Thanks in advance.

MisterToe
  • 43
  • 1
  • 5
  • Sounds like you're passing `shutil` a `datetime.datetime` object instead of a string with the filename. Can you show the code that you were using in that attempt? – TigerhawkT3 Jul 29 '15 at 00:33
  • @TigerhawkT3 I was attempting to use shutil like this: shutil.move(mod_time, 'dest\path') – MisterToe Jul 29 '15 at 00:36
  • As I suspected, you're moving the date. You need to move the file. – TigerhawkT3 Jul 29 '15 at 00:38
  • @TigerhawkT3 That's what I thought but I am unsure how to get the results and apply that to the files that need to be moved? – MisterToe Jul 29 '15 at 00:40

1 Answers1

4

Instead of:

shutil.move(mod_time, 'dest\path')

do:

shutil.move(os.path.join(root, file_name), 'dest\path')

This passes that function a filename instead of a date.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97