Implementing code for batch renaming files in Python _python

Source: Internet
Author: User
The following is the final code (implemented under Windows)
Copy Code code as follows:

#-*-coding:cp936-*-
Import OS
Path = ' d:\\ picture \ \ '
For file in Os.listdir (path):
If Os.path.isfile (Os.path.join (path,file)) ==true:
If File.find ('. ') <0:
Newname=file+ ' rsfdjndk.jpg '
Os.rename (Os.path.join (Path,file), Os.path.join (Path,newname))
Print file, ' OK '
# Print File.split ('. ') [-1]

This is accomplished by first traversing the directory specified by path, if it is a file (not a folder) and there is no '. ' in the filename, which means that the file is appended with the suffix name, and then renamed

Some details need to be noted:

1. If path Specifies a folder that is not the directory where the program is located, the Rename function must have an absolute path in it, otherwise it will report ' Windowserror: [ERROR 2] ' Error

2. If the new filename already exists in the renaming, it will report ' Windowserror: [ERROR 183] ' Error, so the new filename is best to add some random string

3. If you change the file name or suffix name can be split () function for segmentation

The 4.find function returns '-1 ' if the specified string is not found
Bo Master ma6174

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.