0

I recently started with python since I want to become better in geophysics and processing data.

I began with a little sideproject to rename the monthly extract files of my bank account. They have a silly order of date and name and I just want to order them by date.

One of the file names would be AZG149882014_001_20170129.

The last 8 symbols are the date, but in a very unintuitive order, where my winodws system cannot order them properly.

So far the file name changes into 20170129 but does not change the order of the date.

It also does display the year for yy at all. I am a little bit lost. I know that I have to put this also into the replace function, but it won't work with the ways I tried.

Could you help me out?

import os, fnmatch

file_path = 'censored path'

files_to_rename = fnmatch.filter(os.listdir(file_path), '*.pdf')




for file_name in files_to_rename:  
    yy = file_name[-4:-1]
    mm = file_name[-6:-4]
    dd = file_name[-8:-6]
    date=dd + '.' + mm + '.'+ yy
    if fnmatch.fnmatch(file_name, '*2017*'):                
        new_name = os.rename(file_path + file_name, file_path + file_name.replace(file_name[0:17], ''))
        new_name=str(new_name)+str(date)
        print(new_name) 
Aryan
  • 1,093
  • 9
  • 22
janicans
  • 11
  • 2
  • will it work that if i hardcode only the year because assuming that the year won't become a 5 character string untill the year 10,000 so can i just index the year as 4 characters? – Aryan Nov 10 '20 at 13:00
  • and one more question if the date instead of 29 changes to 1 will it just be 1 or be 01? – Aryan Nov 10 '20 at 13:01

1 Answers1

0

Is this what you want?

import os

def rename(path):
    path = path
    date = path.split("_")[-1] # Assuming that the date comes after underscores
    yy, mm, dd = date[0:4], date[4:6], date[6:8] # Assuming that the year 10,00 will not come so fast, so considered the year as 4 character string and the month and date stays a two character string like 01, 12, 09, so on...
    
    result = yy + "." + mm + "." + dd # String Concatenation
    os.rename(path, result) # Rename the file

print(rename("DRIVE:\\User\\Folder\\AZG149882014_001_20170129"))  # Pass the location

OR, a more compact and memory efficient way to do the same thing-

import os

def rename(path):
    os.rename(path, path.split("_")[-1][0:4] + "." + path.split("_")[-1][4:6] + "." + path.split("_")[-1][6:8])

rename("DRIVE:\\User\\Folder\\AZG149882014_001_20170129")

You can expand on this idea and use FOR LOOPS to rename multiple files together although it might more time.

Hope so it helps!
Happy Coding

Aryan
  • 1,093
  • 9
  • 22