在本教程中,我們將學習 Python 中的 shutil
模塊。我們將討論如何執行高級文件操作,例如創建一個新的複製文件並將其歸檔,以及使用 Python 腳本將內容從一個文件複製到另一個文件。讓我們對 shutil
模塊有一個基本的介紹。
Python shutil 模塊提供了執行高級文件操作的工具。它可以操作文件對象,並為我們提供複製和刪除文件的能力。它處理低級語義,如在執行所有操作後創建和關閉文件對象。
Python shutil 模塊附帶了許多內置方法。我們將探索一些重要的方法。要開始使用這個模塊,首先我們需要將它導入到當前的 Python 文件中。
本模塊提供複製()功能,用於將數據從一個文件複製到另一個文件。文件必須在同一個目錄中,並且目標文件必須是可寫的。讓我們理解下面的語法。
語法-
shutil.copyfile(source, destination, *, follow_symlinks = True)
參數:
在上面的語法中-
- 第一個參數是 source,它顯示源文件的路徑。
- 第二個參數是 destination,它顯示目標文件的路徑。
- 第三個參數是可選的;此參數的默認值為真。
- 它返回一個字元串,顯示新創建的文件的路徑。
讓我們理解下面的例子。
示例-
import os
import shutil
# Creating a new folder in the current directory
os.mkdir('javatpoint')
# It will show the empty folder
print('Empty Folder:', os.listdir('javatpoint'))
# testcompare.py file will be copied in the javatpoint folder
shutil.copy('testcompare.py', 'javatpoint')
# After coping the file folder shows the file
print('File Copied Name:', os.listdir('javatpoint'))
輸出:
Empty Folder: []
File Copied Name: ['testcompare.py']
解釋-
copy()函數以目錄名作為參數。這裡元數據不複製,複製的文件將被認為是新創建的文件。此方法還克隆了文件的所有許可權。需要注意的一點是,如果目標文件已經存在,它將被源文件替換。
讓我們看另一個例子。
示例- 2 如果目的地是目錄
import os
import shutil
# hello.txt file will be copied
source = r'D:\Python Project\javatpoint\hello.txt'
# In the newly created foloder
destination = r'D:\Python Project\NewFile'
# Storing the new path of hello.txt file
dest = shutil.copy(source, destination)
# Print the new path
print(dest)
輸出:
D:\Python Project\NewFile\hello.txt
正如我們提到的,copy()函數不複製元數據。但是,我們將使用 copy2() 函數,該函數允許我們複製文件,包括其元數據。
示例- 3:使用複製方法時的錯誤處理
# importing shutil module
import shutil
# It is a source path
source = r"D:\Python Project\NewFolder"
# It is a destination path
destination = r"D:\Python Project\NewFolder"
try:
shutil.copy(source, destination)
print("File copied successfully.")
# If the given source and path are same
except shutil.SameFileError:
print("Source and destination represents the same file.")
# If there is no permission to write
except PermissionError:
print("Permission denied.")
# For other errors
except:
print("Error occurred while copying file.")
輸出:
Source and destination represents the same file.
該功能類似於複製()功能。它還可以將一個文件的內容複製到另一個文件,但唯一的區別是它可以保留文件的元數據。讓我們理解下面的語法。
語法:
shutil.copy2(source, destination, *, follow_symlinks = True)
參數:
在上面的語法中-
- 第一個參數是 source,它顯示源文件的路徑。
- 第二個參數是 destination,它顯示目標文件的路徑。
- 第三個參數是可選的;此參數的默認值為真。
- 它返回一個字元串,顯示新創建的文件的路徑。
讓我們理解下面的例子。
示例-
import os
import shutil
# hello.txt file will be copied
source = r'D:\Python Project\javatpoint\hello.txt'
metadata = os.stat(source)
print(metadata)
# In the newly created foloder
destination = r'D:\Python Project\NewFile'
# Storing the new path of hello.txt file
dest1 = shutil.copy2(source, destination)
metadata = os.stat(dest1)
print("After copying file")
print(metadata)
# Print the new path
print(dest1)
輸出:
os.stat_result(st_mode=33206, st_ino=562949953459285, st_dev=3029671014, st_nlink=1, st_uid=0, st_gid=0, st_size=17, st_atime=1622815671, st_mtime=1622705607, st_ctime=1622705607)
After copying file
os.stat_result(st_mode=33206, st_ino=562949953459287, st_dev=3029671014, st_nlink=1, st_uid=0, st_gid=0, st_size=17, st_atime=1622815748, st_mtime=1622705607, st_ctime=1622706243)
D:\Python Project\NewFile\hello.txt
此方法用於將源文件的內容複製到除元數據之外的目標文件。源和目標必須有文件,目標文件必須提供寫許可權。如果目標文件已經存在,那麼它將被新文件替換,否則創建新文件。
讓我們看看下面的語法。
語法:
shutil.copyfile(source, destination, *, follow_symlinks = True)
參數:
在上面的語法中-
- 第一個參數是 source,它顯示源文件的路徑。
- 第二個參數是 destination,它顯示目標文件的路徑。
- 第三個參數是可選的;此參數的默認值為真。
- 它返回一個字元串,顯示新創建的文件的路徑。
讓我們理解下面的例子。
示例-
import shutil
# hello.txt file will be copied
source = r'D:\Python Project\javatpoint\hello.txt'
# In the newly created foloder
destination = r'D:\Python Project\NewFile\hi.txt'
# Storing the new path of hello.txt file
dest1 = shutil.copyfile(source, destination)
# Print the new path
print(dest1)
輸出:
D:\Python Project\NewFile\hi.txt
此方法用於複製完整的目錄。它將從源位置開始的整個目錄樹複製到目標目錄。目標目錄必須不存在。讓我們看看下面的語法。
語法:
shutil.copytree(src, dst, symlinks = False, ignore = None, copy_function = copy2, igonre_dangling_symlinks = False)
參數:
在上面的語法中:
- src – 顯示源目錄的路徑。
- dest – 顯示目的目錄的路徑。
- 符號鏈接(可選)- 它採用布爾值-真和假。這取決於原始鏈接或鏈接的元數據將被複制到新的樹中。
- 忽略(可選)- 默認情況下為無,但如果忽略被傳遞,它必須是一個可調用的接收作為其參數。copytree()訪問該目錄。
- copy_function(可選)-copy 2 是該參數的默認值。複製()功能可用作參數。
- 忽略 懸空 符號鏈接(可選)- 此參數用於在符號鏈接指向的文件不存在時引發異常。
- 它返回代表新創建的目錄路徑的字元串。
示例-
# importing shutil module
import shutil
# It is source path
src = r'D:\Python Project\javatpoint'
# It is destination path
dest = r'D:\Python Project\NewFolder'
# Copy the content of
# source to destination
dest1 = shutil.copytree(src, dest)
# Now we print path of newly
# created file
print("Destination path:", dest1)
輸出:
Destination path: D:\Python Project\NewFolder
此方法用於刪除完整的目錄樹。讓我們看看下面的語法。
語法:
shutil.rmtree(path, ignore_errors=False, onerror=None)
參數-
在上面的語法中-
- 路徑- 表示文件路徑。類似路徑的對象是字元串或位元組對象。
- 忽略 _ 錯誤- 如果該參數為真,則刪除將被忽略。
- onerror – 如果 ignore_errors 為 false,則通過調用 onerror 指定的處理程序來處理此類錯誤。
讓我們理解下面的例子-
示例-
import shutil
import os
# location
location_dir = r"D:\Python Project\NewFile"
# directory
directory = r"D:\Python Project\javatpoint"
# path
path1 = os.path.join(location_dir, directory)
# removing directory
shutil.rmtree(path1)
上面的代碼將刪除給定的目錄。
shutil . what()函數用於獲取可執行應用的路徑,如果調用給定的 cmd,該程序將運行。它在給定的路徑中找到文件。讓我們看看下面的語法。
語法:
shutil.which(cmd, mode = os.F_OK | os.X_OK, path = None)
參數
在上面的語法中-
- cmd – 是表示文件的字元串。
- 模式- 指定執行方法的文件模式。
- 路徑- 此參數指定要使用的路徑。
- 此方法返回可執行應用的路徑。
讓我們理解下面的例子。
示例-
# importing shutil module
import shutil
# search the file
cmd = 'python'
# Using shutil.which() method
locating = shutil.which(cmd)
# Print result
print(locating)
輸出:
C:\Python\python.EXE
它將在計算機中找到給定的文件,如果找到文件,它將返迴文件的路徑,否則返回無。
原創文章,作者:L9JZX,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/127211.html