python複製資料夾(包含os庫多種函式的)

2022-08-24 13:09:13 字數 1156 閱讀 6232

import os#調出os庫

#檔案的複製

def mycopy(file1,file2):#定義乙個mycopy函式用於複製檔案

f1=open(file1,"rb")#以讀取模式開啟file1

f2=open(file2,"wb")#以清空寫模式開啟file2

content = f1.readline()#將第一行資料賦給content

while len(content)>0:#如果讀取到的資料長度不為0則迴圈執行

f2.write(content)#在file2裡寫下content

content=f1.readline()#再讀一行賦給content

f1.close()#關閉file1

f2.close()

#自定義目錄複製函式

def copydd(dir1,dir2):#定義複製資料夾函式coppydd

#獲取被複製目錄中的所有檔案資訊

dlist = os.listdir(dir1)#以列表模式賦給dlist

#建立新目錄

os.mkdir(dir2)#建立新資料夾dir2

#遍歷所有檔案並執行檔案複製

for f in dlist:#讓f在dlist中遍歷

#為遍歷的檔案新增目錄路徑

file1 = os.path.join(dir1,f)#將f遍歷出的檔名給file1(dir1+f即路徑+檔名)

file2 = os.path.join(dir2,f)#同樣也給file2

#判斷是否是檔案

if os.path.isfile(file1):#判斷是否為檔案的方式為os庫中的函式 os.path.isfile(檔名)

mycopy(file1,file2)#呼叫自定義的mycopy函式複製檔案

if os.path.isdir(file1):#如果是資料夾的話 那就呼叫自身(自身就是複製資料夾嘛)e而處理的不是dir1,dir2,是file1,file2,因為此時資料夾同檔案一起被f遍歷,此處判斷的就是f遍歷出的是檔案還是資料夾

coppydd(file1,file2) #呼叫自身 遞迴思想

#測試copydd("./aa","./bb")#當前資料夾中的aa資料夾複製到bb資料夾 沒有會自動建立

複製資料夾 python中os模組應用

import os 乙個檔案裡面含多個檔案 不含資料夾 src path r c p1 target path r c p2 封裝成函式 def copy src,target if os.path.isdir src and os.path.isdir target filelist os.lis...

Python 檔案及資料夾操作 os

import os os.mkdir 新資料夾 注意如果要建立的資料夾已經存在的話會報錯的 import os if not os.path.exists 新資料夾 os.mkdir 新資料夾 import os os.makedirs 第一層資料夾 第二層資料夾 第三層資料夾 shutil.cop...

Python 檔案或資料夾複製

網上找不到合適直接使用的的檔案複製工具,自己直接手擼了乙個,方便大家使用。功能比較簡單使用,看 應該都能明白。win10 python3.6依賴 os path 和shutil 模組,都是python 環境自帶的,不需要安裝,直接匯入就行 import os,shutil from os impor...