How to arrange pictures using Python in windows 10 or Linux

In this post, I’ll be discussing, how you can efficiently deal with large number of files and Organise them by their month and year and that too in some clicks after you learn to write the code.

Python code to arrange Pictures

Overview: I’ll be explaining a Python code that can efficiently manage pictures (or any files) in a specific directory. That you can specify. For example, your “C://Users//fred//Pictures//” contains 100’s of pictures from different times and you are not sure about when they are last modified and thus you can’t classify them into separate folders by their month/year. Thus you can run this utility code to manage those errors without thinking twice!

Python version I’ll be using:
Python 3.7.6 (default, Dec 19 2019, 23:50:13)

Other modules that are used in the code:
>>> import os
>>> import shutil
>>> from datetime import datetime

Overview of atime, mtime and ctime:

func_desc = os.open(file_path,os.O_RDONLY) # creating function description
descrp = os.fstat(func_desc) # collecting all the file stats
atime = timeStampToDate(descrp.st_atime)
ctime = timeStampToDate(descrp.st_ctime)
mtime = timeStampToDate(descrp.st_mtime) # collecting the modification time as 'timestamp'

so, in the above block of code, you open a file with os.open(file_path,O_RDONLY) and collect and store all the stats of the file opened (here, stored in ‘descrp’). You can separately access them as shown. I have used atime,ctime and mtime.
atime – it is the access time, that means when you last accessed the file.
mtime – it is the last modification time. This parameter signify the timestamp when the file contents were last modified.
ctime – it is the ‘change time’. That is when the specific file’s permission was changed or renamed. This also changes the mtime parameter of the file.
#note: All the values stored in atime, mtime and ctime are ‘timestamps’. So you need to convert it into a datetime object.
I have done this in a separate function and pass it with the timestamp and it will return the datetime object.

def timeStampToDate(timestamp): # getting the timestamp from main function
    date_obj = datetime.fromtimestamp(timestamp) # storing it as datetime object
    return date_obj # returning the same to the main function

Now to classify files into a folder concerning it’s modification time, we need to access the file’s mtime parameter.
Now we’ll see how to get modification year, month, date, time separately.

yr = mtime.year # storing modification year
mnth = mtime.month # storing modification month
hour = mtime.hour # storing modification hour
minute = mtime.minute # storing modification minute
second = mtime.second # storing modification second
mic_seconds = mtime.microsecond # storing modification modification
File_time = list(map(str,[hour,minute,second])) # organising the file modification time in normal form

Creating Separate Folders And Moving Files Into Folders

Now to move files into separate folders, I have called a separate function, passing file path, filename, modification month and modification year to that function.

def create_folder(filepath_, filename, month, year):
    global store,cwd
    folder_name = str(month) + '_' + str(year)
    folder_path = cwd + folder_name + '/'

    if folder_name not in store:
        store.append(folder_name) # appending folder name
        os.mkdir(folder_path) # new folder created
        print(f'Folder: {folder_name} created.'.center(30, '_'))
        shutil.move(filepath_, folder_path + filename) # current file moved
    else: # if folder already exists
        shutil.move(filepath_, folder_path + filename) # current file move

Now if we sum up all the block of codes, this will look like:

import os,shutil,sys
from datetime import datetime
store = [] # global variable to store folder names already created
cwd = '' # global variable to store current working directory


def timeStampToDate(timestamp): # utility function to convert timestamp to datetime object
    date_obj = datetime.fromtimestamp(timestamp)
    return date_obj


def folder_path_modify(folder_path): # modifies folder path allocation (making program open source)
    if sys.platform == 'linux':  # for posix
        if folder_path.endswith('/'):
            return str(folder_path)
        else:
            return str(folder_path + '/')
    elif sys.platform == 'win32':  # for windows
        if folder_path.endswith('\\') or folder_path.endswith('\\\\'):
            return str(folder_path)
        else:
            return str(folder_path + '\\')


def create_folder(filepath, filename, month, year): # this function creates folder and moves files into them
    global store,cwd
    folder_name = str(month) + '_' + str(year)
    folder_path = cwd + folder_name

    if folder_name not in store:
        try:
            store.append(folder_name) # appending folder name
            folder_path = folder_path_modify(folder_path)
            os.mkdir(folder_path) # new folder created
            print(f'Folder: {folder_name} created.'.center(30, '_'))
            # dst_path = folder_path_modify(folder_path + filename)
            shutil.move(filepath, folder_path) # current file moved
            print(folder_path+filename)
            print('File moved !')
        except FileExistsError:
            pass
    else: # if folder already exists
        try:
            folder_path = folder_path_modify(folder_path)
            shutil.move(filepath, folder_path + filename) # current file moved
            print('File moved!')
        except FileExistsError:
            pass


def input_folder(): # taking folder path input from the User
    test_folder = input('Enter Folder path where you want to test the code:')
    if os.path.exists(test_folder):
        test_folder = folder_path_modify(test_folder)
        return test_folder
    else:
        print('Invalid Path Entered, Try again!')
        test_folder = input_folder()
        return test_folder


if __name__ == '__main__':
    folder = input_folder()
    os.chdir(folder)
    cwd = folder_path_modify(os.getcwd()) # storing the current working directory
    print(f'Current working Directory:{cwd}\n')
    for num,file in enumerate(os.listdir(cwd)):
        if os.path.isfile(file):
            print(num+1,'.',file) # printing number_of_files and file name
            file_path = cwd + file # initialising the file path
            func_desc = os.open(file_path,os.O_RDONLY) # creating function description
            descrp = os.fstat(func_desc) # collecting all the file stats
            # length = len(str(descrp)) # collecting the length of the object (for printing)
            # print(str(descrp).center(length+10,' '))
            atime = timeStampToDate(descrp.st_atime)
            ctime = timeStampToDate(descrp.st_ctime)
            mtime = timeStampToDate(descrp.st_mtime) # collecting the modification time as 'timestamp'
            print(str(mtime.date().strftime('%d_%m_%y')).center(20)) # printing the date of modification
            yr = mtime.year # storing modification year
            mnth = mtime.month # storing modification month
            hour = mtime.hour # storing modification hour
            minute = mtime.minute # storing modification minute
            second = mtime.second # storing modification second
            mic_seconds = mtime.microsecond # storing modification modification
            File_time = list(map(str,[hour,minute,second])) # organising the file modification time in normal form
            print(f"{':'.join(File_time).center(20)}") # printing file time
            os.close(func_desc)  # closing the opened file
            # creating folders according to month-yr classification and moving folders
            create_folder(file_path,file,mnth,yr)

 

I have written the folder_path_modify() function to make this program open source, and this can be equally used in POSIX as well as the WINDOWS environment.
Also, I have used sys.platform to find the OS you are working on!

The Input looks like this:

Input_folderdst

And the output will look like this:

#note: this is a part of the output, the full output is not possible to show!

partial_output

File Manager View before Executing the code:

beforecodeRun

File Manager View before Executing the code:

after-codeRun

I hope, you have got the idea and learn how we use Python to arrange pictures in windows 10 or Linux.

 

Also, read: Text watermark on an image in Python using PIL library

 

Leave a Reply

Your email address will not be published. Required fields are marked *