python 怎么将输入目录内的文件拷贝至另一个目录的同名文件夹?
发布网友
发布时间:2022-05-19 09:54
我来回答
共2个回答
热心网友
时间:2023-10-10 05:38
这是最近写的一个类似代码,你拿去改改
import shutil
import os
import logging
import sys
logger = logging.getLogger(__name__)
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
def cp_or_mv2(src_file, des_dir, is_copy):
print(src_file, des_dir)
if os.path.isfile(src_file):
logger.info(f'from file {src_file}')
if is_copy:
shutil.copy2(src_file, des_dir)
logger.info(f'copy to {des_dir}')
else:
des_file = os.path.join(des_dir, src_file)
shutil.move(src_file, des_file)
logger.info(f'move to {des_file}')
else:
logger.info(f'from dir {src_file}')
des_dir_level1 = os.path.join(des_dir, src_file)
shutil.copytree(src_file, des_dir_level1, dirs_exist_ok=True)
logger.info(f'to {des_dir_level1}')
if not is_copy:
shutil.rmtree(src_file)
logger.info(f'deleted {src_file}')
def process_files_in_txt(txt_file, src_dir, des_dir, is_copy=True):
os.chdir(src_dir)
with open(txt_file, 'r', encoding='utf8', errors='ignore') as f:
for line in f.readlines():
src_file = line.strip()
# logger.info(src_file)
if os.path.exists(src_file):
cp_or_mv2(src_file, des_dir, is_copy)
else:
logger.warning(f'{src_file} missing!')
if __name__ == '__main__':
process_files_in_txt(r"D:\D\需要拷贝.txt", # 哪些文件(夹)
r"D:\D\Desktop", # 从哪个文件夹
r"D:\D\新建文件夹", # 到哪个文件夹
is_copy=False) # True复制,False剪切
热心网友
时间:2023-10-10 05:39
把这个脚本放到eew文件夹里运行:
import os
from shutil import copy
for root, dirs, files in os.walk('data'):
for f in files:
file_name = f[:f.index('.')]
copy(os.path.join(root, f), os.path.join('datum', file_name))