Python 个人常用命令
1、记录个人常用的脚本
# -*- encoding=utf-8 -*- import datetime import json import logging import logging.handlers import os import shutil def create_folder(folder): folder = os.path.abspath(folder) if not os.path.exists(folder): try: os.makedirs(folder) msg = 'Success create folder:{}'.format(folder) print(msg) except Exception as e: msg = 'Failed create folder:{}, exception:{}'.format(folder, e) print(msg) def delete_folder(folder): folder = os.path.abspath(folder) if os.path.isdir(folder): try: shutil.rmtree(folder) msg = 'Success delete folder:{}'.format(folder) print(msg) except Exception as e: msg = 'Failed delete folder:{}, exception:{}'.format(folder, e) print(msg) def delete_file(file): file = os.path.abspath(file) if os.path.isfile(file): try: os.remove(file) msg = 'Success delete file:{}'.format(file) print(msg) except Exception as e: msg = 'Failed delete file:{}, exception:{}'.format(file, e) print(msg) def copy_file(src, dst): # 目标文件存在,直接覆盖 # 目标是文件夹,则在文件夹中生成同名文件 create_folder(os.path.dirname(dst)) try: shutil.copy2(src, dst) msg = 'Success copy file:{} to :{}'.format(os.path.abspath(src), os.path.abspath(dst)) print(msg) except Exception as e: msg = 'Fail copy file:{} to :{}, exception:{}'.format(os.path.abspath(src), os.path.abspath(dst), e) print(msg) def copy_folder(src, dst, delete=True): """ :param src: :param dst: :param delete: 目标文件夹存在时,是否删除 :return: """ src = os.path.abspath(src) dst = os.path.abspath(dst) if delete: delete_folder(dst) try: shutil.copytree(src, dst) msg = 'Success copy folder:{} to path:{}'.format(src, dst) print(msg) except Exception as e: msg = 'Fail copy folder:{} to path:{}, exception:{}'.format(src, dst, e) print(msg) def read_file(file, mode='r', line_type=False, encoding=None): file = os.path.abspath(file) if line_type: content = [] else: content = '' if os.path.isfile(file): with open(file, mode, encoding=encoding) as f: if line_type: content = f.readlines() else: content = f.read() return content def write_file(file, info, mode='w', encoding=None, indent=4): create_folder(os.path.dirname(file)) with open(file, mode, encoding=encoding) as f: if isinstance(info, str): f.write(info) elif isinstance(info, list): info = map(lambda x: str(x), info) f.writelines(info) elif isinstance(info, dict): info = json.dumps(info, indent=indent, ensure_ascii=False) f.write(info) else: msg = 'The type I don\'t know' print(msg) def load_json_by_file(file, default=None): if default is None: default = dict() data = default file = os.path.abspath(file) if os.path.isfile(file): with open(file, 'r') as f: try: data = json.load(f) msg = 'Success load json file:{}'.format(file) print(msg) except Exception as e: msg = 'Failed load json file:{} exception:{}'.format(file, e) print(msg) else: msg = 'Can not find file:{} for load json'.format(file) print(msg) return data def load_json_by_string(string, default=None): if default is None: default = dict() data = default try: data = json.loads(string) msg = 'Success load json string:{}'.format(string) print(msg) except Exception as e: msg = 'Failed load json string:{}, exception:{}'.format(string, e) print(msg) return data def now(fmt='%Y%m%d%H%M%S'): string = datetime.datetime.now().strftime(fmt) return string def string_to_date(string, fmt='%Y-%m-%d %H:%M:%S'): # 2021-01-28 10:51:26 date = datetime.datetime.strptime(string, fmt) return date def date_to_string(date, fmt='%Y-%m-%d %H:%M:%S'): # 2021-01-28 10:51:26 string = date.strftime(fmt) return string def traverse_folder(folder, only_first=False): folder = os.path.abspath(folder) all_files = [] all_dirs = [] if os.path.isdir(folder): for root, dirs, files in os.walk(folder): for one_file in files: all_files.append(os.path.join(root, one_file)) # 所有文件 for one_dir in dirs: all_dirs.append(os.path.join(root, one_dir)) # 所有文件夹 if only_first: break else: msg = 'Can not find folder:{} for traverse'.format(folder) print(msg) return all_dirs, all_files def init_logger(log_name='logs/log.log', logger_string='ROOT', max_bytes=1024 * 1024 * 1, backup_count=10, mode='a', fmt_string='[%(asctime)s][%(name)s][%(levelname)s]%(message)s', record_level=logging.INFO, console_level=logging.WARN, file_level=logging.INFO): """ CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0 :param fmt_string: :param logger_string: :param mode: :param log_name: :param max_bytes: :param backup_count: :param record_level: :param console_level: :param file_level: :return: """ create_folder(os.path.dirname(log_name)) fmt = logging.Formatter(fmt_string) # 设置日志格式 logger = logging.getLogger(logger_string) logger.setLevel(record_level) stream_handler = logging.StreamHandler() # 控制台日志句柄,设置则可以打印到控制台 stream_handler.setLevel(console_level) # 设置打印到控制台日志等级 stream_handler.setFormatter(fmt) if stream_handler not in logger.handlers: logger.addHandler(stream_handler) # 添加控制台句柄 # 设置回滚日志句柄 rollback_handler = logging.handlers.RotatingFileHandler(log_name, mode, max_bytes, backup_count) rollback_handler.setLevel(file_level) # 设置回滚日志记录INFO以及以上信息 rollback_handler.setFormatter(fmt) if rollback_handler not in logger.handlers: logger.addHandler(rollback_handler) # 添加回滚日志句柄 return logger # 返回句柄,以便于使用 log = init_logger() if __name__ == '__main__': log.info('!!!!') log.info('!!!!1') log.info('!!!!2') log.info('!!!!3')
2、修改文件的创建时间,修改时间,访问时间
# -*- encoding=utf-8 -*- import os import time from pywintypes import Time # 可以忽视这个 Time 报错(运行程序还是没问题的) from win32con import FILE_FLAG_BACKUP_SEMANTICS from win32con import FILE_SHARE_WRITE from win32file import CloseHandle from win32file import CreateFile from win32file import GENERIC_WRITE from win32file import OPEN_EXISTING from win32file import SetFileTime def get_file_time(filename): filename = os.path.abspath(filename) create_time = os.path.getctime(filename) # 创建时间 print('old create time:{}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(create_time)))) update_time = os.path.getmtime(filename) # 修改时间 print('old update time:{}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(update_time)))) access_time = os.path.getatime(filename) # 访问时间 print('old access time:{}'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(access_time)))) return create_time, update_time, access_time def modify_file_create_time(filename, create_time_str, update_time_str, access_time_str): try: format_str = "%Y-%m-%d %H:%M:%S" # 时间格式 # f = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, 0) f = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_WRITE, None, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0) create_time = Time(time.mktime(time.strptime(create_time_str, format_str))) update_time = Time(time.mktime(time.strptime(update_time_str, format_str))) access_time = Time(time.mktime(time.strptime(access_time_str, format_str))) SetFileTime(f, create_time, update_time, access_time) CloseHandle(f) print('update file time success:{}/{}/{}'.format(create_time_str, update_time_str, access_time_str)) except Exception as e: print('update file time fail:{}'.format(e)) if __name__ == '__main__': get_file_time('测试.txt') cTime = "2019-12-13 21:51:02" # 创建时间 mTime = "2019-02-02 00:01:03" # 修改时间 aTime = "2019-02-02 00:01:04" # 访问时间 modify_file_create_time("测试.txt", cTime, mTime, aTime) get_file_time('测试.txt')