For a long time photo, sometimes I want to recall it ~ Generally, photos are automatically divided into folders by time. It is very troublesome to copy folders one by one. You can write a python script to complete this task.
This is the root directory of the folder to be copied. Each subdirectory contains several photos.
To put it bluntly, go to 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 and go to disk F to see it:
The photos have been copied, and there are indeed a lot of photos (there are still a lot below, not finished)
The code is easy to understand, mainly OS. walk () function. This function returns the three tuples in the specified path (Starting path, directory in the starting path, and file name list without path name in the starting path)
It can recursively traverse all directories and file names under a specified directory, which is easy to use.
It can be seen that python only needs a few lines of code to complete this work, which is very convenient. If you use C ++ to implement code, it will be longer than this.
You can also use OS. listdir (dirname): Implemented by the function. The listdir function lists the directories and files under dirname, and then uses a judgment: if it is a file, copy it; if it is a directory, continue Recursion
It is obviously not convenient to use the walk () function. However, I don't know how the walk () function is implemented internally. It may not be good to directly store all the files in the root directory in list neutral performance. You can use listdir () to compare and test it later.
You should know which method to choose ~ Very simple ~ But it is quite practical ~
Recommended reading:
Python Regular Expression usage tutorial