1. 程式人生 > 程式設計 >Python實現自動整理檔案的指令碼

Python實現自動整理檔案的指令碼

前言

工作上的文件和資料好幾個月沒整理了,因為平常太忙都是隨手往桌面丟。整個桌面雜亂無章全是文件和資料。幾乎快佔滿整個螢幕了,所有我必須要整理一下了。但是手動整理太費時間了,於是我想到了python。

示例

import os
import glob
import shutil

'''
@Author: huny
@date: 2020.12.06
@function: 桌面整理
'''


class FileType():
  def __init__(self):
    self.filetype = {
      "圖片": [".jpeg",".jpg",".tiff",".gif",".bmp",".png",".bpg","svg",".heif",".psd"],"視訊": [".avi",".flv",".wmv",".mov",".mp4",".webm",".vob",".mng",".qt",".mpg",".mpeg",".3gp",".mkv"],"音訊": [".aac",".aa",".aac",".dvf",".m4a",".m4b",".m4p",".mp3",".msv",".ogg",".oga",".raw",".vox",".wav",".wma"],"文件": [".oxps",".epub",".pages",".docx",".doc",".fdf",".ods",".odt",".pwi",".xsn",".xps",".dotx",".docm",".dox",".rvg",".rtf",".rtfd",".wpd",".xls",".xlsx",".ppt",".pptx",".csv",".pdf",".md",".xmind"],"壓縮檔案": [".a",".ar",".cpio",".iso",".tar",".gz",".rz",".7z",".dmg",".rar",".xar",".zip"],"文字": [".txt",".in",".out",".json",".xml",".log"],"程式指令碼": [".py",".html5",".html",".htm",".xhtml",s".c",".cpp",".java",".css",".sql"],"可執行程式": [".exe",".bat",".lnk"],"字型檔案": [".ttf",".OTF",".WOFF",".EOT"]
    }

  def JudgeFile(self,pathname):
    for name,type in self.filetype.items():
      if pathname in type:
        return name
    return "無法判斷型別檔案"


class DeskTopOrg(object):
  def __init__(self):
    self.filetype = FileType()

  def Organization(self):   
    filepath = os.path.join(os.path.expanduser('~'),"Desktop")
    paths = glob.glob(filepath + "/*.*")
    # print('paths-->',paths)
    for path in paths:
      try:
        if not os.path.isdir(path):
          file = os.path.splitext(path)
          filename,type = file
          # print('type-->',type)
          # print("filename-->",filename)
          print('path-->',path)
          dir_path = os.path.dirname(path)
          # print('dir_path-->',dir_path)
          savePath = dir_path + '/{}'.format(self.filetype.JudgeFile(type))
          print('savePath-->',savePath)
          if not os.path.exists(savePath):
            os.mkdir(savePath)
            shutil.move(path,savePath)
          else:
            shutil.move(path,savePath)
      except FileNotFoundError:
        pass
    # print("程式執行結束!")


if __name__ == '__main__':
  try:
    while True:
      desktopOrg = DeskTopOrg()
      desktopOrg.Organization()
      print("---->你的桌面已經整理完成。")
      a = input('---->請按回車鍵退出:')
      if a == '':
        break
  except BaseException:
    print("ERROE:路徑錯誤或有重複的文件")

整理完了,桌面清爽了不少。(注意此指令碼是按字尾進行分類歸檔的)

Python實現自動整理檔案的指令碼

進階

基於這個我想是否可以對其他不同的路徑進行整理呢,於是又優化了一下

import os
import glob
import shutil

'''
@Author: huny
@date: 2020.12.06
@function: 檔案整理
'''


class FileType():
  def __init__(self):
    self.filetype = {
      "圖片": [".jpeg","xml",".c",type in self.filetype.items():
      if pathname in type:
        return name
    return "無法判斷型別檔案"


class DeskTopOrg(object):
  def __init__(self):
    self.filetype = FileType()

  def Organization(self):
    filepath = input("請輸入需要整理的資料夾路徑: ")
    paths = glob.glob(filepath + "/*.*")
    print('paths-->',type = file
          print('type-->',type)
          print("filename-->",path)
          dir_path = os.path.dirname(path)
          print('dir_path-->',savePath)
      except FileNotFoundError:
        pass
    print("程式執行結束!")


if __name__ == '__main__':
  try:
    while True:
      desktopOrg = DeskTopOrg()
      desktopOrg.Organization()
      print("---->你的檔案已經整理完成。")
      a = input('---->請按回車鍵退出:')
      if a == '':
        break
  except BaseException:
    print("ERROE:路徑錯誤或有重複的文件")

可以自由的整理你想要整理的路徑。

Python實現自動整理檔案的指令碼

後續

其他朋友也有需求,但是又沒有python環境,於是我將程式打包成exe執行檔案。

安裝pyinstaller

pip install pyinstaller

執行打包命令

#在程式指令碼的路徑執行以下命令
pyinstaller -F ***.py   

執行完後生成幾個檔案,在dist檔案下有一個exe可執行檔案,將他單獨發給朋友即可。

Python實現自動整理檔案的指令碼

別忘了先自己測試一遍。

Python實現自動整理檔案的指令碼

以上就是Python實現自動整理檔案的指令碼的詳細內容,更多關於python 自動整理檔案的資料請關注我們其它相關文章!