一、Python複製文件夾
複製整個文件夾可以使用shutil庫中的shutil.copytree源目錄和目標目錄函數。該函數將源目錄中的所有內容複製到目標目錄。
import shutil # 將srcdir目錄及其所有內容複製到dstdir shutil.copytree(srcdir, dstdir)
二、如何將文件複製到Python
我們可以使用Python的open函數來打開文件,並在寫入模式下使用write函數將文件內容寫入Python腳本中。
with open('file_to_copy.txt', 'w') as f: f.write('This is the content of the file')
三、Python複製文件到另一個目錄
可以使用shutil庫中的shutil.copy函數將文件從源路徑複製到目標路徑。
import shutil src_file = "file_to_copy.txt" dst_folder = "/new/location/" shutil.copy(src_file, dst_folder)
四、Python複製移動文件
使用shutil庫中的shutil.move函數可以將文件從一個目錄移動到另一個目錄。該函數另外還可以支持文件重命名。
import shutil src_file = "/existing/location/file_to_move.txt" dst_folder = "/new/location/" # 移動文件並重命名 shutil.move(src_file, dst_folder + "new_file_name.txt")
五、Python複製文件路徑
os模塊中的os.path.dirname和os.path.abspath函數可以獲取源文件的路徑。
import os path = "/path/to/file.txt" src_folder = os.path.dirname(os.path.abspath(path))
六、Python文件複製
使用shutil庫中的shutil.copy函數可以複製文件到目標目錄。另外,可以使用os.path拼接路徑。
import shutil import os src_file = "/path/to/file.txt" dst_folder = "/new/location/" filename = os.path.split(src_file)[1] shutil.copy(src_file, os.path.join(dst_folder, filename))
七、Python複製文件夾功能
使用shutil庫中的shutil.copytree函數可以將整個文件夾複製到目標目錄。
import shutil src_folder = "/path/to/folder/" dst_folder = "/new/location/" shutil.copytree(src_folder, dst_folder)
八、Python複製文件夾並重名
使用os模塊中的shutil.copytree函數和os.rename函數可以複製文件夾並在目標目錄中重命名。 注意:copytree中的目標目錄必須不存在,並且源目錄名稱將成為目標目錄的一部分。
import shutil import os src_folder = "/path/to/folder/" dst_folder = "/new/location/new_folder_name" shutil.copytree(src_folder, dst_folder) os.rename(dst_folder + '/' + os.path.basename(src_folder), dst_folder + '/' + 'new_folder_name')
九、Python複製文件內容
使用Python的open函數和read函數可以讀取文件中的文本,並將其寫入另一個文件。
with open('source_file.txt', 'r') as f: text = f.read() with open('destination_file.txt', 'w') as f: f.write(text)
十、Python複製文件到指定目錄
使用Python的shutil庫中的copy2函數可以將文件複製到目標目錄。copy2函數介紹:它嘗試儘可能保留文件元數據,例如所有權和時間戳等屬性。
import shutil src_file = "/path/to/file.txt" dst_folder = "/new/location/" shutil.copy2(src_file, dst_folder)
原創文章,作者:YEBQ,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/138559.html