Change the file extension for files in a folder?

后端 未结 5 1700
逝去的感伤
逝去的感伤 2020-12-05 00:31

I would like to change the extension of the files in specific folder. i read about this topic in the forum. using does ideas, I have written following code and I expect that

5条回答
  •  有刺的猬
    2020-12-05 01:30

    #!/usr/bin/env python
    
    '''
    Batch renames file's extension in a given directory
    '''
    
    import os
    import sys
    from os.path import join
    from os.path import splitext
    
    def main():
        try:
            work_dir, old_ext, new_ext = sys.argv[1:]
        except ValueError:
            sys.exit("Usage: {} directory old-ext new-ext".format(__file__))
    
        for filename in os.listdir(work_dir):
            if old_ext == splitext(filename)[1]:
                newfile = filename.replace(old_ext, new_ext)
                os.rename(join(work_dir, filename), join(work_dir, newfile))
    
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题