Bulk renaming of files based on lookup

前端 未结 9 481
忘掉有多难
忘掉有多难 2020-12-11 05:55

I have a folder full of image files such as

  • 1500000704_full.jpg
  • 1500000705_full.jpg
  • 1500000711_full.jpg
  • 1500000712_full.jpg
9条回答
  •  长情又很酷
    2020-12-11 06:48

    A rewrite of Wesley's using generators:

    import os, os.path
    
    with open('mapping.txt') as mapping_file:
        mapping = dict(line.strip().split() for line in mapping_file)
    
    rootextiter = ((filename, os.path.splitext(filename)) for filename in os.listdir('.'))
    mappediter = (
        (filename, os.path.join(mapping[root], extension))
        for filename, root, extension in rootextiter
        if root in mapping
    )
    for oldname, newname in mappediter:
        os.rename(oldname, newname)
    

提交回复
热议问题