For Python beginners to study, I started by organizing files!
I don't know if there is a demand, but I tried to divide it into folders with the structure of extension / year_month
, so I will keep a record as a reminder.
import shutil
import os
import glob
import datetime
import sys
#Reference site
####################################################
#Shutil to move files and directories in Python.move
# https://note.nkmk.me/python-shutil-move/
####################################################
#How to use glob module in Python [For beginners]
# https://techacademy.jp/magazine/18928
####################################################
def mv_file(ex):
df_path = 'bk/' + ex
os.makedirs(df_path, exist_ok=True)
# mv_Search for a file with the extension specified by the argument of the file function (in the same folder)
for x in glob.glob('*.' + ex):
print(x)
#Get the time stamp of the file creation date
dt = datetime.datetime.fromtimestamp(os.path.getctime(x))
if dt: #If you can get the creation date
#From the time stamp "Year_Format conversion to month
fm = dt.strftime('%Y_%m')
path = df_path + '/' + fm
else: #If the creation date could not be obtained
path = df_path + '/others'
#Generate directory (ignored if it already exists)
os.makedirs(path, exist_ok=True)
#Move the file to "path"
new_path = shutil.move(x, path)
#Below, function execution
mv_file('pdf')
mv_file('zip')
mv_file('jpg')
mv_file('png')
mv_file('xls')
mv_file('xlsx')
mv_file('xlsm')
mv_file('doc')
mv_file('docx')
mv_file('ppt')
mv_file('pptx')
mv_file('csv')
#Wait until the Enter key is pressed to check the operation
input("Press Enter to continue...")
There are many parts that have not been created, such as naming conventions and error prevention, so if you want to use the source, please check the operation with a file that can be damaged before using it!
Recommended Posts