Code for batch renaming objects using python

Source: Internet
Author: User

The following is the final code (implemented in windows) Copy codeThe Code is as follows: #-*-coding: cp936 -*-
Import OS
Path = 'd: \ image \\'
For file in OS. listdir (path ):
If OS. path. isfile (OS. path. join (path, file) = True:
If file. find ('.') <0:
Newname1_file='rsfdjndk.jpg'
OS. rename (OS. path. join (path, file), OS. path. join (path, newname ))
Print file, 'OK'
# Print file. split ('.') [-1]

The implementation method is: first traverse the directory specified by path, if it is a file (not a folder) and the file name does not exist '. ', that is, if there is no suffix, add the suffix name to the file and rename it.

Pay attention to some details:

1. If the folder specified by path is not the directory of the program, the path in the rename function must be an absolute path. Otherwise, the 'windowserror: [Error 2] 'Error will be reported.

2. If the new file name already exists during renaming, The 'windowserror: [Error 183] 'Error will be reported. Therefore, it is best to add some random strings to the new file name.

3. You can use the split () function to split the file name or suffix.

4. If the find function cannot find the specified string, '-1' is returned'
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.