Recursive copy of the python implementation file

  • 2020-04-02 09:40:33
  • OfStack

So I just want to flip through the photos and look at them again, but the photos are copied out of the phone

Is automatically divided into folders by time, a folder copy is very troublesome, so I decided to write a python script to complete the work (drag so much, finally

Here we go, the wicks.)

< img Alt = "" border = 0 SRC =" / / img.jbzj.com/file_images/article/201208/201208022327135.png ">

This is the root directory of the folder to be copied, with several photos in each subdirectory.

Nonsense, on the code:
 
# -*- coding: utf-8 -*- 
#!/usr/bin/python 
#Filename:copyfile.py 
import os,shutil 
def mycopy(srcpath,dstpath): 
if not os.path.exists(srcpath): 
print "srcpath not exist!" 
if not os.path.exists(dstpath): 
print "dstpath not exist!" 
for root,dirs,files in os.walk(srcpath,True): 
for eachfile in files: 
shutil.copy(os.path.join(root,eachfile),dstpath) 
srcpath='e:\pic' 
dstpath='f:\pictotal' 
mycopy(srcpath,dstpath) 

Run this script, go to the f disk to see:

< img Alt = "" border = 0 SRC =" / / img.jbzj.com/file_images/article/201208/201208022327136.png ">

I copied all the photos, and sure enough, there are a lot of photos (there are many more at the bottom, they are not finished).
There's nothing too complicated about the code, mainly the os.walk () function, which returns the triplet of the specified path (the starting path, the directory under the starting path, and the list of file names under the starting path without the path name)
It can recursively traverse to the specified directory under all directories and file names, more useful.
Also can use os.listdir(dirname) : function to achieve, listdir function listed under the dirname directory and files, and then through a judgment: if the file, copy; If the directory, continue the recursion
Walking is obviously not as easy to use as the walk () function. But I don't know how the walk () function is implemented internally, and it might not perform well to simply store all the files in the root directory in the list,
You can compare this with listdir ().

As you can see, python is handy for doing this in just a few lines of code. If you do it in C++, the code is longer than that.
So, language doesn't matter how high or low, it's good to achieve your goals efficiently and conveniently, right?

Related articles: