Batch Renaming of Files in a Directory

前端 未结 13 1471
孤街浪徒
孤街浪徒 2020-11-27 09:41

Is there an easy way to rename a group of files already contained in a directory, using Python?

Example: I have a directory full of *.doc files an

13条回答
  •  爱一瞬间的悲伤
    2020-11-27 10:11

    directoryName = "Photographs"
    filePath = os.path.abspath(directoryName)
    filePathWithSlash = filePath + "\\"
    
    for counter, filename in enumerate(os.listdir(directoryName)):
    
        filenameWithPath = os.path.join(filePathWithSlash, filename)
    
        os.rename(filenameWithPath, filenameWithPath.replace(filename,"DSC_" + \
              str(counter).zfill(4) + ".jpg" ))
    
    # e.g. filename = "photo1.jpg", directory = "c:\users\Photographs"        
    # The string.replace call swaps in the new filename into 
    # the current filename within the filenameWitPath string. Which    
    # is then used by os.rename to rename the file in place, using the  
    # current (unmodified) filenameWithPath.
    
    # os.listdir delivers the filename(s) from the directory
    # however in attempting to "rename" the file using os 
    # a specific location of the file to be renamed is required.
    
    # this code is from Windows 
    

提交回复
热议问题