Python 複製檔案和目錄

2021-10-18 03:37:02 字數 1980 閱讀 3988

無非就是乙個讀取檔案和寫入檔案的操作

def

copy_file

(src_path,target_path)

:# 如果檔案過大建議使用ab進行寫入,一次讀取1024個位元組

fp1 =

open

(src_path,

'rb'

)# fp2 = open(file_path2,'wb')

fp2 =

open

(target_path,

'ab'

)while

true

: content = fp1.read(

1024)if

not content:

break

fp2.write(content)

# content = fp1.read()

# fp2.write(content)

注意:使用自己的目錄路徑(這裡我就直接使用上面的複製檔案的函式了)

# 遍歷sourcepath下的所有子目錄和子檔案

# 1, 如果是子檔案,則複製檔案

# 2, 如果是子目錄,在目標目錄建立相同的目錄名稱,遞迴呼叫

# 注意:子檔案或子目錄的絕對路徑

import os

defcopy_file

(src_path,target_path)

:# 如果檔案過大建議使用ab進行寫入,一次讀取1024個位元組

fp1 =

open

(src_path,

'rb'

)# fp2 = open(file_path2,'wb')

fp2 =

open

(target_path,

'ab'

)while

true

: content = fp1.read(

1024)if

not content:

break

fp2.write(content)

# content = fp1.read()

# fp2.write(content)

defcopypath

(sourcepath, targetpath)

:# 判斷原目錄是否存在

ifnot os.path.exists(sourcepath)

:return

"目錄不存在"

# 判斷目標目錄是否存在,如果不存在則建立

ifnot os.path.exists(targetpath)

: os.mkdir(targetpath)

list_dir = os.listdir(sourcepath)

fordir

in list_dir:

file_path1 = os.path.join(sourcepath,

dir)

file_path2 = os.path.join(targetpath,

dir)

if os.path.isfile(file_path1)

: copy_file(file_path1,file_path2)

else

:# 是資料夾就進行遞迴

copypath(file_path1,file_path2)

if __name__ ==

"__main__"

:# 將sourcepath目錄的所有內容拷貝到targetpath目錄下

sourcepath = r"e:\cloudmusic\2101\1python基礎\第03周\day13"

targetpath = r"e:\cloudmusic\2101\1python基礎\第03周\day13-1"

copypath(sourcepath, targetpath)

qaq

檔案目錄複製

private void copydir string srcpath string aimpath 判斷目標目錄是否存在如果不存在則新建 if system.io directory exists aimpath 得到源目錄的檔案列表,該裡面是包含檔案以及目錄路徑的乙個陣列 如果你指向copy目標...

實現目錄拷貝 複製目錄 複製檔案

include include include include include include include ifndef debug define pdebug fmt,args.do while 0 else define pdebug fmt,args.printf s d fmt,func...

python複製目錄

複製目錄 1.定義乙個函式 引數1 指定需要複製的目錄,引數2 目標目錄位置 2.判斷指定目錄是否存在 不存在 終止 3.判斷目標目錄是否存在,不存在 建立 4.遍歷目錄 5.如果是目錄 繼續遍歷且需要在目標目錄中建立新的 6.如果是檔案,複製 讀寫檔案 import os def copydir ...