-2

I'm new to coding, and only know VBA at best.

However I would like a python script which will rename all the excel files in a folder. It needs to include the date the file was last modified at the start of the string. The date format will be YYYYMMDD.

For example, if the original file name is "CWI001-CA-E1140", the ammended file name should be "20150422_CWI001-CA-E1140".

I'm using windows 8, thanks in advance.

  • 1
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask]. – Morgan Thrapp Aug 03 '15 at 13:12
  • Please regard that tag [tag:batch-file] does _not_ apply here (reference its description); use tag [tag:batch-processing] instead. Thank you! – aschipfl Aug 03 '15 at 13:42

1 Answers1

0

Using os.listdir to get a list of file in a directory, and os.rename to rename files.

import datetime
import os

DIRECTORY = '.'

for filename in os.listdir(DIRECTORY):

    # Skip non-xls file
    if not filename.lower().endswith('.xls'):
        continue

    path = os.path.join(DIRECTORY, filename)
    mtime = os.path.getmtime(path)  # modification time
    prefix = datetime.datetime.fromtimestamp(mtime).strftime('%Y%m%d')
    newpath = os.path.join(DIRECTORY, prefix + '_' + filename)

    # rename it
    os.rename(path, newpath)
falsetru
  • 357,413
  • 63
  • 732
  • 636