import os
defcopyFile(srcFile,destFile):fileInput=open(srcFile,mode='rb+')fileOutput=open(destFile,mode='wb+')fileOutput.write(fileInput.read())fileOutput.close()fileInput.close()defcopyDir(srcDir,destDir):for s in os.listdir(srcDir):newPath = os.path.join(srcDir, s)destPath = os.path.join(destDir, s)if os.path.isdir(newPath):os.mkdir(destPath)copyDir(newPath,destPath)elif os.path.isfile(newPath):copyFile(newPath,destPath)
srcDir=input("請輸入需要復制的文件夾:")
destDir=input("請輸入目標空文件夾:")
copyDir(srcDir,destDir)
案例:遞歸刪除多個文件
遍歷刪除含有多個文件的文件夾
# author:dq# project:PythonProject# date:2021年10月28日# function:遍歷刪除含有多個文件的文件夾。import ospath ='D:/CodeProject/Python_DQ/PythonProject/pythonProject/lesson13/path2'#path=input('請輸入文件路徑')defdelete(path):# 判斷文件是否存在if os.path.exists(path):# 如果是文件,就直接刪除if os.path.isfile(path):os.remove(path)# 如果是文件夾elif os.path.isdir(path):# 如果文件夾為空就就直接刪除ifnot os.listdir(path):os.rmdir(path)# 如果文件夾不為空,就進入新的文件夾遞歸else:for i in os.listdir(path):#拼接獲取新的文件路徑newPath=os.path.join(path,i)delete(newPath)#再逐一刪除外層的文件夾os.rmdir(path)delete(path)
CSV文件
關系型數據庫:表格,二維數據
CSV文件讀取與寫入(學習)
newline=‘’識別換行符,空字符串
使用代碼:
#author:dq#project:PythonProject#date:2021年11月01日#function:csv文件的讀寫#讀取csvimport csvpath='./information.csv'file=open(path,'w',encoding='utf-8',newline='')
w=csv.writer(file)w.writerow(['name','age','gender'])
w.writerow(['dq',20,'female'])
w.writerow(['dd',20,'man'])
w.writerow(['rwq',20,'female'])file.close()#寫入CSVfile=open(path,'r',encoding='utf-8',newline='')
r=csv.reader(file)for data in r:print(data)