This articleIntroductionPython shutil module learningSummary
##shutil The name comes from shell utilities, if you have studied or understood it## People from #Linuxshould be familiar with the shell, and you can use this to memorize the name of the module. This module has many file (folder) operation functions, including copy, move, rename, delete, etc.
(source, destination)shutil.copy() Function
implements the file copy function and copies the source file to the destination folder. Both parameters are in string format. If destination is a file name, then it will be used as the copied file name, which is equal to copy + rename. For example: >> import shutil
>> os.
chdir
('C:\') >> shutil.copy('C:\spam.txt', 'C:\delicious')'C:\delicious\spam.txt'
>> shutil.copy('eggs .txt', 'C:\delicious\eggs2.txt')
'C:\delicious\eggs2.txt'
As shown in the code, the return value of the
Note that if the destination folder already exists, this operation will return a
ExistsError error, indicating that the file already exists. That is to say, if this function is executed, the program will automatically create a new folder (destination parameter) and copy the contents of the source folder to itFor example:
>> shutil.copytree('C:\bacon', ' C:\bacon_backup')
\'C:\bacon_backup'
如以上代码所示,该函数的返回值是复制成功后的文件夹的绝对路径字符串 所以该函数可以当成是一个备份功能
上例中,如果 C:\eggs 文件夹中已经存在了同名文件 bacon.txt,那么该文件将被来自于 source 中的同名文件所重写。 如果 destination 指向一个文件,那么 source 文件将被移动并重命名,如下:
'C:\eggs\new_bacon.txt'等于是移动+重命名
<b>注意,如果 destination 是一个文件夹,即没有带后缀的路径名,那么 source 将被移动并重命名为 destination</b>,如下:
' C:\eggs'
即 bacon.txt 文件已经被重命名为 eggs,是一个没有文件后缀的文件 最后,destination 文件夹必须是已经存在的,否则会引发异常:
>> shutil.move('spam.txt', 'C:\does_not_exist\eggs\ham')
Traceback (most recent c
last):
File "D:\Python36\lib\shutil.py", line 538, in moveos.rename(src, real_dst)FileNotFoundError: [WinError 3] The system cannot find it The specified path. : 'test.txt' -> 'C:\does_not_exist\eggs\ham'
During han
dl
ing of the above
exception, another exception occurred: Traceback (most recent call last):File "
os.rmdir(path) will delete the path path folder, but this folder must be empty and does not contain any files or subfolders
shutil.rmtree(path ) will delete the path path folder, and all files and subfolders in this folder will be deleted
swith
attributeof the string to modify the file format Checking and filtering
The above is the detailed content of Python shutil module learning summary. For more information, please follow other related articles on the PHP Chinese website!