Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How python copies folders

Shulou Source: shulou.com Published: 2022-05-31 11:12:53 10月25日 Update

This article mainly introduces the python how to copy the folder related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this python how to copy the folder article will have a harvest, let's take a look.

Specific operation methods:

1. First of all, you need to import os into the python script, and the shutil module performs file operations.

Import os, shutil

2. Use the copy function to copy the folder.

Shutil.copy (source_file,target_ir) # source_file refers to the source path and target_ir refers to the destination path

Example code:

1. Copy the folder as a whole.

Import os

Import shutil

Source_path = os.path.abspath (ringing E:\ Projects\ source_dir')

Target_path = os.path.abspath (ringing E:\ Projects\ new folder\ target_dir')

If not os.path.exists (target_path):

# create if the destination path does not exist in the original folder

Os.makedirs (target_path)

If os.path.exists (source_path):

# delete if the original folder exists in the destination path

Shutil.rmtree (target_path)

Shutil.copytree (source_path, target_path)

Print ('copy dir finishedmakers')

2. Copy all the files under the folder to the destination folder.

Import os

Import shutil

Source_path = os.path.abspath (ringing E:\ Projects\ source_dir')

Target_path = os.path.abspath (ringing E:\ Projects\ target_dir')

If not os.path.exists (target_path):

Os.makedirs (target_path)

If os.path.exists (source_path):

# root refers to the address of the folder that is currently being traversed

# dirs is a list that contains the names of all directories in this folder (excluding subdirectories)

# files is also list and contains all files in this folder (excluding subdirectories)

For root, dirs, files in os.walk (source_path):

For file in files:

Src_file = os.path.join (root, file)

Shutil.copy (src_file, target_path)

Print (src_file)

Print ('copy files finishedmakers')

Related functions:

Os.remove # Delete files

Os.rmdir # Delete folder

Shutil.rmtree # Delete the directory and all its contents

This is the end of the article on "how to copy folders in python". Thank you for reading! I believe you all have a certain understanding of "how to copy folders in python". If you want to learn more, you are welcome to follow the industry information channel.

Tags: File folder content target path knowledge function subdirectory subdirectory copy directory article code value name address instance reference easy to operate overall Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Xiaomi MariaDB macOS Shulou Technology