'''FileIntroduce:這個文件主要是用來實現拷貝文件,拷貝文件夾,新建,刪除文件等os操作'''
#author:ytouch
#date:2019/4/26
#using suggestion: 包含路徑的參數均為絕對路徑,因為要使得該py文件具有通用性import os
import shutil
from shutil import copyfilecur_file_name = '' #設定該變量為全局變量,表示當前文件名,用于copyFileToFolder方法中'''Func:在指定路徑下新建文件夾功能'''
def newFolderpath(folder_path):#param1:指定新建文件夾路徑is_Exist = os.path.exists(folder_path) #判斷該文件夾是否存在if not is_Exist: #不存在時創建該文件夾os.mkdir(folder_path)else:print("當前文件夾已存在,文件夾路徑為:" + folder_path)'''Func:新建任意后綴文件'''
def newFile(new_file_path):#param1:新建的文件路徑cur_file = open(new_file_path,'w')cur_file.close()'''Func:復制文件到指定文件路徑下'''
def copyFileToFile(file_path,new_file_path):#param1:需要復制的文件路徑#param2:指定的文件路徑下copyfile(file_path,new_file_path)'''Func:復制文件到指定文件夾路徑下'''
def copyFileToFolder(file_path,new_folder_path):#param1:需要復制的文件路徑#param2:指定的文件夾路徑下global cur_file_nameif file_path.find('/') >= 0: #判斷路徑格式 / or \\list_file_path = file_path.split('/')cur_file_name = list_file_path[len(list_file_path)-1] #取出對應文件名else:list_file_path = file_path.split('\\')cur_file_name = list_file_path[len(list_file_path)-1]if new_folder_path.find('/') >= 0: #判斷路徑格式 / or \\if new_folder_path.endswith('/'):new_copy_path = new_folder_path + cur_file_namecopyfile(file_path, new_copy_path)else:new_copy_path = new_folder_path + '/' + cur_file_namecopyfile(file_path, new_copy_path)else:if new_folder_path.endswith('\\'):new_copy_path = new_folder_path + cur_file_namecopyfile(file_path, new_copy_path)else:new_copy_path = new_folder_path + '\\' + cur_file_namecopyfile(file_path,new_copy_path)'''Func:復制文件夾到指定文件夾路徑下:(并且包含里面的文件)'''
def copyFolderToFolder(folder_path,new_folder_path):#param1:需要復制的文件夾路徑#param2: 新的文件夾路徑if not os.path.exists(folder_path):print("folder_path not exist!")if not os.path.exists(new_folder_path):print("new_folder_path not exist!")for root,dirs,files in os.walk(folder_path,True):for eachfile in files:shutil.copy(os.path.join(root,eachfile),new_folder_path)'''Func:刪除指定空的文件夾'''
def deleteEmptyFolder(folder_path):#param1:需要刪除的空的文件夾路徑os.rmdir(folder_path)'''Func:刪除包含文件內容的文件夾'''
def deleteFolder(folder_path):#param1:需要刪除的文件夾路徑shutil.rmtree(folder_path,True)'''Func:刪除指定的文件'''
def deleteFile(file_path):#param1:刪除文件的路徑is_Exist = os.path.exists(file_path) #先判斷是否該文件存在if not is_Exist:print("當前文件路徑不存在")else:os.remove(file_path)
?
使用方法:
首先將該文件保存下來,命名為FileManage.py即可
新建新的py文件,在同級目錄下,
使用方法如下:
import FileManage as fileMethodfileMethod.copyFileToFile('E:/123/44.txt','E:/123/55.txt') #直接調用方法即可
python全棧開發、希望能對大家有所幫助,同時大家也可以學一下我寫的代碼風格哈哈哈
?
實現了copyFolderToFolder(folder_path,new_folder_path)這個方法
?
python真的好用哈哈哈
?
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态