Python Batch Rename file example

Source: Internet
Author: User
Tags glob join


Python Batch Rename file method is very simple we will use Listdir and rename directory traversal can be implemented to achieve the file command, the following collation of some methods.



Two interfaces to the OS are used:



1, list all the files in the folder (also contains the directory)



Os.listdir (PATH)



Return a list containing the names of the "entries in" directory given by Path. The list is in arbitrary order. It does not include the special entries '. ' and ' ... ' even if they are in the directory.



Availability:unix, Windows.



Changed in version 2.3:on Windows nt/2k/xp and Unix, if path was a Unicode object, the result would be a list of Unicode OB Jects. Undecodable filenames'll still be returned as String objects



2, rename the file



Os.rename (SRC, DST)



Rename the file or directory src to DST. If DST is a directory, OSError'll be raised. On Unix, if DST exists and is a file, it would be replaced silently if the user has permission. The operation may fail on some Unix flavors if SRC and DST are on different filesystems. If successful, the renaming would be a atomic operation (this is a POSIX requirement). On Windows, if DST already exists, OSError would be raised even if it is a file; There may is no way to implement a atomic rename when DST names a existing file.



Availability:unix, Windows


The code is as follows
Import OS

Dirpath= "D:/workbench/crazyant.net/myfiles"
For fname in Os.listdir (Dirpath):
Newfname=fname[3:]
Newfpath= "%s/%s"% (dirpath,newfname)
Oldfpath= "%s/%s"% (dirpath,fname)

Os.rename (Oldfpath, Newfpath)


In fact, using Os.listdir to read all the files inside, and then use Os.rename file Rename can be achieved



3, for the above method I also found some ways


  code is as follows

# coding=utf-8 
  
Import os 
Impo RT re 
  
Path = "D:temp"
pattern = Re.compile (' d{3} ')  
  
to file in O S.listdir (path):  
    if Os.path.isfile (os.path.join (path, file)):  
         match = pattern.search (file)  
        Assert match 
        name = Match.group () + '. mp3 '
         #print file, name 
        os.rename ( Os.path.join (path, file), Os.path.join (path, name))


Pay attention to the difference between match and search: Match is to start from scratch, search is greed. Well, it's not that complicated. There's a thing called bulk Rename utility to rename.



Add one more



Enter the specified directory in which the program processes the directory and its subdirectories that contain big.jpg files.



Rename the file named ' Big (5). jpg ' to ' big_5.jpg ',



That is big (N). jpg ==> big_n.jpg



The code is as follows:



# coding:cp936



"""



File renaming



Enter the specified directory in which the program processes the directory and its subdirectories that contain big.jpg files.



Rename the file named ' Big (5). jpg ' to ' big_5.jpg ',



That is big (N). jpg ==> big_n.jpg



@author Chenwei



@date 2010-12-26



"""



Import Glob



Import OS



def main ():



Print ' Rename task start '



Base_dir = raw_input (' Please enter the directory to be processed: ')



# Working with top-level catalogs



Rename_dir (Base_dir)



# Find subdirectories that contain big.jpg files



Pattern = Base_dir + R ' *big.jpg '



File_list = Glob.glob (pattern)



# Processing each directory separately



For file in File_list:



i = File.rindex (')



dir = file[:i]



Rename_dir (dir)



print ' Rename task complete '



Raw_input (' Enter arbitrary content end ')



def rename_dir (dir):



# Find the file to be renamed according to the pattern



pattern = dir + R ' Big (*). jpg '



File_list = Glob.glob (pattern)



# processing each file separately



For file in File_list:



Rename_file (file)



def rename_file (fname):



# get filename, remove path and extension



i = Fname.rindex (')



j = Fname.rindex ('. ')



basename = Fname[i+1:j]



# Get File Number



k = Basename.rindex (' (')



L = Basename.rindex (') ')



Seq = basename[k+1:l]



# New file name



New_fname = Fname.replace (Fname[i+1:j], ' Big_ ' +seq)



# renaming



Try



Os.rename (fname, New_fname)



print ' rename ' + fname + ' to ' + new_fname + ' success '



Except



print ' rename ' + fname + ' to ' + new_fname + ' fail '



if __name__ = = ' __main__ ':



Main ()


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.