I tried to divide the file into folders with Python

Introduction

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.

Source code


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...")

Finally

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

I tried to divide the file into folders with Python
I tried to touch the CSV file with Python
I tried to solve the soma cube with python
I tried to solve the problem with Python Vol.1
I tried to solve the ant book beginner's edition with python
I tried to improve the efficiency of daily work with Python
I tried "smoothing" the image with Python + OpenCV
I tried "differentiating" the image with Python + OpenCV
I tried to save the data with discord
I tried to get CloudWatch data with Python
I tried to output LLVM IR with Python
I tried to automate sushi making with python
I want to write to a file with Python
[Python] I tried to visualize the night on the Galactic Railroad with WordCloud!
I tried to refer to the fun rock-paper-scissors poi for beginners with Python
I tried to get the authentication code of Qiita API with Python.
I tried with the top 100 PyPI packages> I tried to graph the packages installed on Python
I tried to streamline the standard role of new employees with Python
I tried to get the movie information of TMDb API with Python
I tried fp-growth with python
I tried scraping with Python
I tried gRPC with Python
I tried scraping with python
I tried to learn the sin function with chainer
I tried to graph the packages installed in Python
I tried to implement Minesweeper on terminal with python
I tried to get started with blender python script_Part 01
I tried to draw a route map with Python
I tried to implement an artificial perceptron with python
I want to inherit to the back with python dataclass
I tried to put pytest into the actual battle
I tried to analyze J League data with Python
I tried hitting the API with echonest's python client
I tried to summarize the string operations of Python
I tried to solve AOJ's number theory with Python
I tried to easily visualize the tweets of JAWS DAYS 2017 with Python + ELK
I tried searching for files under the folder with Python by file name
I tried to automatically send the literature of the new coronavirus to LINE with Python
I tried to open the latest data of the Excel file managed by date in the folder with Python
I tried to find out how to streamline the work flow with Excel x Python ②
I tried "gamma correction" of the image with Python + OpenCV
I tried to analyze the whole novel "Weathering with You" ☔️
Extract the xz file with python
I tried using the Python library from Ruby with PyCall
I wanted to solve the Panasonic Programming Contest 2020 with Python
I tried to make various "dummy data" with Python faker
I tried to find the average of the sequence with TensorFlow
I tried various methods to send Japanese mail with Python
I tried to touch Python (installation)
I tried to find out how to streamline the work flow with Excel x Python ④
[Python] Write to csv file with Python
I tried to notify the train delay information with LINE Notify
Create folders from '01' to '12' with python
I tried to find out how to streamline the work flow with Excel x Python ⑤
I tried to put out the frequent word ranking of LINE talk with Python
Output to csv file with Python
[Markov chain] I tried to read negative emotions into Python.
I tried to automate the article update of Livedoor blog with Python and selenium.
[Markov chain] I tried to read a quote into Python.
What I did to welcome the Python2 EOL with confidence
[Python] I want to use the -h option with argparse