Python腳本:linux上將篩選的文件夾復制到另一個目錄,保存目錄結構以及文件和文件夾操作方法


import os,shutil

def newDir(dir_path):
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)

def copydir(where_path,go_path,start_time,end_time):
    newDir(go_path)
    for brand in os.listdir(where_path):
        brand_path = os.path.join(where_path, brand)
        #print('brand_path',brand_path)
        for site in os.listdir(brand_path):
            site_path = os.path.join(brand_path,site)
            #print('site_path',site_path)
            for child in os.listdir(site_path):
                file_time = '-'.join(child.split('-')[2:5])
                go_dir = go_path + '/' + brand + '/' + site#動態生成子目錄
                print(file_time[:10])
                if file_time[:10] >= start_time and file_time[:10] <= end_time:
                    child_path = os.path.join(site_path,child)

                    if not os.path.isdir(child_path):
                        #print('file',child_path)
                        newDir(go_dir)
                        shutil.copy(child_path,go_dir)
                    else:
                        #print('dir',child_path)
                        #復制文件夾能夠自己生成目錄
                        shutil.copytree(child_path,go_dir+'/'+child)

#刪除文件名包含2018的文件和文件夾
def deldir(path):
    for child in os.listdir(path):
        child_path = os.path.join(path,child)
        if '2018' in child:
            if not os.path.isdir(child_path):
                os.unlink(child_path)
            else:
                shutil.rmtree(child_path)

if __name__ == "__main__":
    copydir('/lingtian/static_files/mkcms_dev/memo/memo_htmls','/lingtian/static_files/mkcms_dev','2018-09-01','2018-09-30')
    #deldir('/lingtian/static_files/mkcms_dev')                            

 我要復制的目錄三層,所以有三層循環,保留了原來的目錄結構

附上python相關文件操作,文件的復制和移動使用shutil包 ,刪除使用os包

#文件、文件夾的移動、復制、刪除、重命名 
#導入shutil模塊和os模塊
import shutil,os 
#復制單個文件 
shutil.copy("C:\\a\\1.txt","C:\\b") 
#復制並重命名新文件 
shutil.copy("C:\\a\\2.txt","C:\\b\\121.txt") 
#復制整個目錄(備份) 
shutil.copytree("C:\\a","C:\\b\\new_a") 
#刪除文件 
os.unlink("C:\\b\\1.txt") 
os.unlink("C:\\b\\121.txt") 
#刪除空文件夾 
try: 
    os.rmdir("C:\\b\\new_a") 
except Exception as ex: 
    print("錯誤信息:"+str(ex))
#提示:錯誤信息,目錄不是空的 
#刪除文件夾及內容 
shutil.rmtree("C:\\b\\new_a") 
#移動文件
shutil.move("C:\\a\\1.txt","C:\\b") 
#移動文件夾 
shutil.move("C:\\a\\c","C:\\b") 
#重命名文件 shutil.move("C:\\a\\2.txt","C:\\a\\new2.txt") 
#重命名文件夾 
shutil.move("C:\\a\\d","C:\\a\\new_d") 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM