80 lines
2.4 KiB
Python
80 lines
2.4 KiB
Python
#encoding=utf-8
|
|
import shutil
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
class FileCopier:
|
|
def __init__(self):
|
|
self.path = Path.cwd()
|
|
self.file_path = self.path / 'file.txt'
|
|
self.dir_list = list(range(1, 61))
|
|
|
|
def init_dir(self):
|
|
"""初始化目录"""
|
|
for dir_num in self.dir_list:
|
|
dir_path = self.path / str(dir_num)
|
|
if dir_path.exists():
|
|
shutil.rmtree(dir_path)
|
|
dir_path.mkdir()
|
|
print("目录初始化完成")
|
|
|
|
def _copy_files(self, file_list):
|
|
"""复制文件到目录中"""
|
|
if not self.file_path.exists():
|
|
raise FileNotFoundError(f"源文件 {self.file_path} 不存在")
|
|
|
|
file_dir_map = dict(zip(file_list, self.dir_list))
|
|
success_count = 0
|
|
|
|
for file_num, dir_num in file_dir_map.items():
|
|
new_name = f'file_{file_num}.txt'
|
|
target_path = self.path / str(dir_num) / new_name
|
|
try:
|
|
shutil.copyfile(self.file_path, target_path)
|
|
success_count += 1
|
|
except Exception as e:
|
|
print(f"复制文件 {file_num} 到目录 {dir_num} 失败: {e}")
|
|
|
|
print(f"成功复制 {success_count} 个文件")
|
|
|
|
def copy_odd(self):
|
|
"""复制奇数文件"""
|
|
file_list = list(range(1, 121, 2))
|
|
print(f"开始复制 {len(file_list)} 个奇数文件...")
|
|
self._copy_files(file_list)
|
|
|
|
def copy_even(self):
|
|
"""复制偶数文件"""
|
|
file_list = list(range(2, 121, 2))
|
|
print(f"开始复制 {len(file_list)} 个偶数文件...")
|
|
self._copy_files(file_list)
|
|
|
|
def main():
|
|
"""主函数"""
|
|
if len(sys.argv) != 2:
|
|
print("用法: python copy_files.py [init|js|os]")
|
|
print(" init - 初始化目录")
|
|
print(" js - 复制奇数文件")
|
|
print(" os - 复制偶数文件")
|
|
sys.exit(1)
|
|
|
|
command = sys.argv[1].lower()
|
|
copier = FileCopier()
|
|
|
|
try:
|
|
if command == 'init':
|
|
copier.init_dir()
|
|
elif command == 'js':
|
|
copier.copy_odd()
|
|
elif command == 'os':
|
|
copier.copy_even()
|
|
else:
|
|
print(f"错误: 未知命令 '{command}'")
|
|
print("请使用 init, js 或 os")
|
|
sys.exit(1)
|
|
except Exception as e:
|
|
print(f"执行失败: {e}")
|
|
sys.exit(1)
|
|
|
|
if __name__ == '__main__':
|
|
main() |