Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename files, Python/Jython

I have a directory full of files, some which have an ampersand in their names. I would like to rename all the files with ampersands and replace each ampersand with a plus (+). I am working with around 10k files. What would be the best method to do this?

like image 287
RailsSon Avatar asked Mar 13 '09 09:03

RailsSon


3 Answers

import glob, os
for filename in glob.glob(os.path.join(yourPath, "*&*")):
   os.rename(filename, filename.replace('&','+'))
like image 129
vartec Avatar answered Sep 24 '22 00:09

vartec


If you have subdirectories:

import os
for dirpath, dirs, files in os.walk(your_path):
    for filename in files:
        if '&' in filename:
            os.rename(
                os.path.join(dirpath, filename),
                os.path.join(dirpath, filename.replace('&', '+'))
            )
like image 23
Ali Afshar Avatar answered Sep 23 '22 00:09

Ali Afshar


import os
directory = '.'
for file in os.listdir(directory):
    if '&' in file :
        os.rename(file, file.replace('&', '+'))

Replace directory with your own path.

like image 33
sykora Avatar answered Sep 23 '22 00:09

sykora