How to use the shutil module for file and directory operations in Python 2.x
Introduction:
In Python, the shutil module is a powerful file and directory operation tool. It provides a set of simple and easy-to-use functions that can be used to copy, move, and delete files, as well as create, delete, and traverse directories.
import shutil # 复制文件 shutil.copy('source_file.txt', 'destination_file.txt')
In the above code example, we use the shutil.copy() function to copy the file named source_file.txt
to the file named destination_file.txt
file. If the target file does not exist, this function will automatically create one.
import shutil # 移动文件 shutil.move('old_location.txt', 'new_location.txt')
In the above example, we used the shutil.move() function to move the file named old_location.txt
to the file named new_location.txt
s position. If the target file already exists, this function will overwrite the file.
import shutil # 删除文件 shutil.remove('file_to_delete.txt')
In the above code example, we used the shutil.remove() function to delete the file named file_to_delete.txt
.
import shutil # 创建目录 shutil.mkdir('new_directory')
In the above code example, we used the shutil.mkdir() function to create a new directory named new_directory
.
import shutil # 复制目录 shutil.copytree('source_directory', 'destination_directory')
In the above example, we used the shutil.copytree() function to copy the source_directory
directory and its contents to the destination_directory
directory.
import shutil # 移动目录 shutil.move('old_directory', 'new_directory')
In the above code example, we used the shutil.move() function to move a directory named old_directory
to a directory named new_directory
s position.
import shutil # 删除目录 shutil.rmtree('directory_to_delete')
In the above code example, we used the shutil.rmtree() function to delete the directory named directory_to_delete
and its contents.
Summary:
The shutil module is a very convenient tool in Python that can be used to perform file and directory operations. Whether it is copying, moving, deleting files or creating or deleting directories, the shutil module provides simple and easy-to-use functions. I hope the above sample code can help you better understand and use the shutil module.
The above is the detailed content of How to use shutil module for file and directory operations in Python 2.x. For more information, please follow other related articles on the PHP Chinese website!