Python batch file rename example

Source: Internet
Author: User

Python batch file rename example

Python batch file rename method is very simple. We will use listdir and rename plus directory traversal to implement file re-command. Below we have sorted out some methods.

Two OS interfaces are used:

1. List all files in the folder (including directories)

OS. listdir (path)

Return a list containing the names of the entries in the directory given by path. the list is in arbitrary order. it does not include the special entries '. and '.. 'Even if they are present in the directory.

Availability: Unix, Windows.

Changed in version 2.3: On Windows NT/2 k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects. undecodable filenames will 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 will be raised. on Unix, if dst exists and is a file, it will 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 will be an atomic operation (this is a POSIX requirement ). on Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an 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, you can use OS. listdir to read all the files, and then use OS. rename to rename the files.

3. I also found some methods for the above methods.

The Code is as follows:  

# Coding = UTF-8

Import OS
Import re

Path = "D: temp"
Pattern = re. compile ('d {3 }')

For file in OS. listdir (path ):
If OS. path. isfile (OS. path. join (path, file )):
Match = pattern. search (file)
Assert match
Name = match. group () + 'hangzhou'
# Print file, name
OS. rename (OS. path. join (path, file), OS. path. join (path, name ))

Note the difference between match and search: match matches from the beginning, and search is greedy. In fact, it's not that complicated. A theme called Bulk Rename Utility is used for renaming.

Add another

Enter the specified directory, and the program processes the Directory and Its subdirectories containing big.jpg files,

Rename the file named 'big(52.16.jpg 'to 'big_5.jpg ',

Big(N).jpg ==> big_N.jpg

The Code is as follows:

# Coding: cp936

"""

File rename

Enter the specified directory, and the program processes the Directory and Its subdirectories containing big.jpg files,

Rename the file named 'big(52.16.jpg 'to 'big_5.jpg ',

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 ('Enter the directory to be processed :')

# Process top-level Directories

Rename_dir (base_dir)

# Search for subdirectories containing big.jpg files

Pattern = base_dir + R' * big.jpg'

File_list = glob. glob (pattern)

# Process each directory separately

For file in file_list:

I = file. rindex ('')

Dir = file [: I]

Rename_dir (dir)

Print 'rename task completed'

Raw_input ('end of any input content ')

Def rename_dir (dir ):

# Find the file to be renamed by Mode

Pattern = dir + r'big (* 2.16.jpg'

File_list = glob. glob (pattern)

# Process files separately

For file in file_list:

Rename_file (file)

Def rename_file (fname ):

# Get the file name, remove the path and extension

I = fname. rindex ('')

J = fname. rindex ('.')

Basename = fname [I + 1: j]

# Getting file numbers

K = basename. rindex ('(')

L = basename. rindex (')')

Seq = basename [k + 1: l]

# New File Name

New_fname = fname. replace (fname [I + 1: j], 'Big _ '+ seq)

# Rename

Try:

OS. rename (fname, new_fname)

Print 'rename '+ fname + 'to' + new_fname + 'successful'

Except t:

Print 'rename '+ fname + 'to' + new_fname + 'failed'

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.