目录
Python想获取当前目录下所有目录的所需文件复制或移动到另一个文件夹下面 ,需要使用到 os.work() 方法遍历所有文件。
一、任务目标
将test1文件下所有目录中 .TXT 文件拷贝到 test2 文件夹下。
一级目录
二级目录
三级目录
然后需要将目录下所有 .TXT 文件复制或移动到一个新的文件夹下面。
二、复制文件代码实现
import os
import shutil
def mycopyfile(srcfile, dstpath): # 复制函数
if not os.path.isfile(srcfile):
print("%s not exist!" % (srcfile))
else:
fpath, fname = os.path.split(srcfile) # 分离文件名和路径
if not os.path.exists(dstpath):
os.makedirs(dstpath) # 创建路径
shutil.copy(srcfile, dstpath + fname) # 复制文件
print("copy %s -> %s" % (srcfile, dstpath + fname))
src_dir = r"E:/data/test1" # 源文件路径
dst_dir = r"E:/data/test2/" # 目的路径记得加斜杠
for root,dirs,files in os.walk(src_dir):
for file in files:
print(file)
# 使用join函数将文件名称和文件所在根目录连接起来
if file.endswith('TXT'):
mycopyfile(os.path.join(root, file),dst_dir)
三、实现效果
C:\ProgramData\Anaconda3\envs\pytorch-cpu\python.exe F:/Study/move_test.py
1.TXT
copy E:/data/test1\1.TXT -> E:/data/test2/1.TXT
3.TXT
copy E:/data/test1\1\3.TXT -> E:/data/test2/3.TXT
4.TXT
copy E:/data/test1\2\4.TXT -> E:/data/test2/4.TXT
2.TXT
copy E:/data/test1\2\2\2.TXT -> E:/data/test2/2.TXT
Process finished with exit code 0
然后打开目的文件夹,发现所有 .TXT 文件均已拷贝到目的文件夹下
四、移动文件代码实现
若想移动目录下的内容,只需将 shutil.copy() 替换为 shutil.move()
import os
import shutil
def mymovefile(srcfile, dstpath): # 移动函数
if not os.path.isfile(srcfile):
print("%s not exist!" % (srcfile))
else:
fpath, fname = os.path.split(srcfile) # 分离文件名和路径
if not os.path.exists(dstpath):
os.makedirs(dstpath) # 创建路径
shutil.move(srcfile, dstpath + fname) # 移动文件
print("move %s -> %s" % (srcfile, dstpath + fname))
src_dir = r"E:/data/test1" # 源文件路径
dst_dir = r"E:/data/test2/" # 目的路径记得加斜杠
for root,dirs,files in os.walk(src_dir):
for file in files:
print(file)
# 使用join函数将文件名称和文件所在根目录连接起来
if file.endswith('TXT'):
mymovefile(os.path.join(root, file),dst_dir)
打印结果
C:\ProgramData\Anaconda3\envs\pytorch-cpu\python.exe F:/Study/move_test.py
1.TXT
move E:/data/test1\1.TXT -> E:/data/test2/1.TXT
3.TXT
move E:/data/test1\1\3.TXT -> E:/data/test2/3.TXT
4.TXT
move E:/data/test1\2\4.TXT -> E:/data/test2/4.TXT
2.TXT
move E:/data/test1\2\2\2.TXT -> E:/data/test2/2.TXT
Process finished with exit code 0
文件夹 test1 下 .TXT 内容均已移动到指定文件夹 test2 下
参考文档: