Re-name files within folder

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sscpord
    New Member
    • Jul 2010
    • 2

    Re-name files within folder

    I am new to python and still learning but I have a problem that I think should be able to be solved using a python script. I have a main folder on my desktop called “CREATED” and within this folder there are two other folders called “USED” and “UNUSED”. Within each of these folders there are a large number of files that have all have a five-letter prefix to the file name i.e. “DAFET”

    What I would like to do is to create a python script to read all the files in the two sub folders and remove the five letter prefix at the beginning of the file name to leave the rest of the file name intact.

    Is this possible?

    Any help would be greatly appreciated
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Yes. This should be relatively easy with standard path commands. I'll post back something that should get you started. In the mean time get yourself familiar with writing and running python scripts!

    Comment

    • Glenton
      Recognized Expert Contributor
      • Nov 2008
      • 391

      #3
      okay, something like this should do the trick:

      Code:
      import os
      
      mypath=os.getcwd()+"/USED"
      for fname in os.listdir(mypath):
          oldf=mypath+"/"+fname
          newf=mypath+"/"+fname[5:]
          print oldf,newf
          #os.rename(oldf,newf)
      Put this into the CREATED folder. Run it with the rename line commented out. It will show you the before and after without doing anything. If it's right, then uncomment the rename line and it should fly!

      Warnings:
      1. I only did one of your directories
      2. The slash might be the other way for windows.
      3. Better check to make sure that there's no name clash with the new names.
      4. I'm working quickly here!

      Comment

      • sscpord
        New Member
        • Jul 2010
        • 2

        #4
        Hi Glenton

        Thanks a lot for taking the trouble to help. What you have suggested is really helpful

        Comment

        Working...