代码包含日志终端输出、日志文件输出和命令行参数解析示例
主要功能,根据命令行参数复制对应比例的文件到指定的文件夹中,并输出相应日志
python
import os
import random
import shutil
import logging
import argparse
def copy_random_files(input_folder, output_folder, percentage=10):
# 获取输入文件夹中的所有文件
all_files = os.listdir(input_folder)
# 计算需要复制的文件数量
num_files_to_copy = int(len(all_files) * percentage / 100)
# 随机选择要复制的文件
files_to_copy = random.sample(all_files, num_files_to_copy)
if os.path.isdir(output_folder):
#删除输出文件夹内容
shutil.rmtree(output_folder)
# 确保输出文件夹存在,如果不存在则创建
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 复制文件到输出文件夹
for file_name in files_to_copy:
input_path = os.path.join(input_folder, file_name)
output_path = os.path.join(output_folder, file_name)
shutil.copy(input_path, output_path)
logging.info(f"Copying {input_path} to {output_path}")
def setup_logging(log_file, log_level):
logging.basicConfig(filename=log_file, level=log_level, format='%(asctime)s - %(levelname)s - %(message)s')
console_handler = logging.StreamHandler()
console_handler.setLevel(log_level)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
logging.getLogger('').addHandler(console_handler)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Copy a random percentage of files from one folder to another.')
parser.add_argument('-i', '--input', default='img_npz_3008', help='Input folder path')
parser.add_argument('-o', '--output', default='img_calibrate', help='Output folder path')
parser.add_argument('-p', '--percentage', type=int, default=10, help='Percentage of files to copy (default: 10)')
parser.add_argument('-lf', '--log-file', default='copy_random_files.log', help='Log file path (default: copy_random_files.log)')
parser.add_argument('-ll','--log-level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], default='INFO', help='Log level (default: INFO)')
args = parser.parse_args()
setup_logging(args.log_file, getattr(logging, args.log_level))
logging.info(f"Copying {args.percentage}% of files from {args.input} to {args.output}")
copy_random_files(args.input, args.output , args.percentage)