2022年 11月 5日

python复制、移动文件到指定文件夹

之前修改博客 python 复制/移动文件 – clq.lib – 博客园 的代码,为保存故作记录。

1、复制文件到指定文件夹

  1. # srcfile 需要复制、移动的文件
  2. # dstpath 目的地址
  3. def mycopyfile(srcfile,dstpath): # 复制函数
  4. if not os.path.isfile(srcfile):
  5. print ("%s not exist!"%(srcfile))
  6. else:
  7. fpath,fname=os.path.split(srcfile) # 分离文件名和路径
  8. if not os.path.exists(dstpath):
  9. os.makedirs(dstpath) # 创建路径
  10. shutil.copy(srcfile, dstpath + fname) # 复制文件
  11. print ("copy %s -> %s"%(srcfile, dstpath + fname))
  12. src_dir = './'
  13. dst_dir = './copy/' # 目的路径记得加斜杠
  14. src_file_list = glob(src_dir + '*') # glob获得路径下所有文件,可根据需要修改
  15. for srcfile in src_file_list:
  16. mycopyfile(srcfile, dst_dir) # 复制文件

2、移动文件到指定文件夹

  1. # srcfile 需要复制、移动的文件
  2. # dstpath 目的地址
  3. def mymovefile(srcfile,dstpath): # 移动函数
  4. if not os.path.isfile(srcfile):
  5. print ("%s not exist!"%(srcfile))
  6. else:
  7. fpath,fname=os.path.split(srcfile) # 分离文件名和路径
  8. if not os.path.exists(dstpath):
  9. os.makedirs(dstpath) # 创建路径
  10. shutil.move(srcfile, dstpath + fname) # 移动文件
  11. print ("move %s -> %s"%(srcfile, dstpath + fname))
  12. src_dir = './'
  13. dst_dir = './move/' # 目的路径记得加斜杠
  14. src_file_list = glob(src_dir + '*') # glob获得路径下所有文件,可根据需要修改
  15. for srcfile in src_file_list:
  16. mymovefile(srcfile, dst_dir) # 移动文件

提示:

1、如需移动一个文件,只需将glob中的 ‘*’ 更改为 具体文件名

2、如需移动多个文件,只需根据文件名规则更改glob

3、使用命令行移动文件