• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

describe

This topic describes how to copy all files in the source directory to the target path. If the target path does not exist, create the file.

Py will import your entire copy_Folder.py code and run it in main.py to transfer all files in the directory.

The sample

Your review will execute your code by executing the command python copy_Folder. py {from_dir_path} {to_dir_path}, passing from_dir_path and to_dir_path as command-line arguments, You can see how the code works in main.py.

The sample a

When the input file path is:

/data/testcase1/ /output/dir1/
Copy the code

The output data is:

comparator output: success
Copy the code

The sample 2

When the input file path is:

/data/testcase2/ /output/dir2/
Copy the code

The output data is:

comparator output: success
Copy the code

Answer key

There are two main points:

  1. Copy all files in the directory
  2. The target path does not exist.

The os.listdir() method is used to return a list of files or folder names that the specified folder contains. It does not include.. and.. Even if it’s in a folder. It can only be used in Unix or Windows.

Os.path.isfile () : checks whether an object (with an absolute path) is a file. Shutil. copyfile(SRC, DST) : Copies file contents (excluding metadata) from SRC to DST.

Shutil. copytree Copies all files and folders under the folder

Shutil.copyfileobj (FSRC, FDST [, length]) : Copies the file content (excluding metadata) from the SRC class file object to the DST class file pair.

import shutil import os def copy_folder(from_dir_path, to_dir_path): # write your code here file_list = os.listdir(from_dir_path) if os.path.exists(to_dir_path)==False: Os.makedirs (to_dir_path) for I in file_list: # print(type(I)) if(os.path.isfile(from_dir_path+"/"+ I)): shutil.copyfileobj(open(from_dir_path+"/"+i,'r'), open(to_dir_path+"/"+i,'a')) else: shutil.copytree(from_dir_path+"/"+i,to_dir_path+"/"+i) # shutil.copytree(from_dir_path, to_dir_path)Copy the code