Replacing Filename characters with python

前端 未结 4 1074
借酒劲吻你
借酒劲吻你 2021-02-06 02:43

I have some code which adds the word \"_manual\" onto the end of a load of filenames.. I need to change the script so that it deletes the last two letters of the filename (ES)

4条回答
  •  心在旅途
    2021-02-06 03:09

    For a more generalized take on hughdbrown's answer. This code can be used to remove any particular character or set of characters.

    import os
    
    paths = (os.path.join(root, filename)
            for root, _, filenames in os.walk('C:\FolderName')
            for filename in filenames)
    
    for path in paths:
        # the '#' in the example below will be replaced by the '-' in the filenames in the directory
        newname = path.replace('#', '-')
        if newname != path:
            os.rename(path, newname)
    

提交回复
热议问题