修复当前目录下载文件名被url转义的文件

#!/usr/bin/env python3
# encoding: utf-8

"""
[@version](https://my.oschina.net/u/931210): ??
[@author](https://my.oschina.net/arthor): Licamla(在湖闻樟)
[@license](https://my.oschina.net/u/176938): 
[@contact](https://my.oschina.net/u/3400572): [email protected]
@project: tool
@software: PyCharm
@file: unescape_file.py
@time: 18-3-21 下午8:59
"""
import os
from urllib.parse import unquote

class FileRenameHandler:
    def __init__(self, root_dir=None):
        if not root_dir:
            root_dir = os.getcwd()
        self._root_dir = root_dir

    def rename(self):
        for root_dir, dirs, files in os.walk(self._root_dir):
            print('root dir {}'.format(self._handle_string_to_unicode(root_dir)))
            self._rename_files(files)
            self._rename_dirs(dirs)

    def _rename_files(self, files):
        for file_name in files:
            self._rename_file(file_name)

    def _rename_dirs(self, dirs):
        for dir_name in dirs:
            renamed_dir_path = self._rename_file(dir_name)
            FileRenameHandler(renamed_dir_path).rename()

    def _rename_file(self, file_name):
        root_dir = self._root_dir
        unquote_file_name = unquote(file_name)
        full_name = os.path.join(root_dir, file_name)
        if file_name != unquote_file_name:
            full_unquote_file_name = os.path.join(root_dir, unquote_file_name)
            print('rename {} to {}'.format(full_name, full_unquote_file_name))
            os.rename(full_name, full_unquote_file_name)
            return full_unquote_file_name
        print('ignore {}'.format(self._handle_string_to_unicode(full_name)))
        return full_name

    @staticmethod
    def _handle_string_to_unicode(string:str) -> str:
        return string.encode(errors='ignore').decode()


if __name__ == '__main__':
    handler = FileRenameHandler()
    handler.rename()

在湖闻樟注:

猜你喜欢

转载自my.oschina.net/soarwilldo/blog/1648819