Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

One, foreword

Today we will take you to realize the operation of automatic file sorting. In our daily life, documents are always messy, this time we need to tidy up. However, too many files can be very cumbersome to organize, so we will implement automatic file sorting in Python today.

2. Traverse the file

To organize a file, we first need to walk through the file. Here use two methods, one is to directly get all files and folders under the specified directory. The other is to get files, folders and subfiles, folders under the specified directory…

Let’s look directly at the code here:

import os
basedir = "test1"
file_list = [os.path.join(basedir, i) for i in os.listdir(basedir)]
print(file_list)
Copy the code

The output is as follows:

['test1\\a1.jpeg'.'test1\\a2.jpeg'.'test1\\a3.jpeg']
Copy the code

Let’s look at the second one:

import os
basedir = r"D:\\"
for root, dirs, files in os.walk(basedir):
    for file in files:
        path = os.path.join(root, file)
        print(path)
Copy the code

Here, we directly traverse the files under disk D, and the output results are as follows:

EM.rst.txt
D:\\CodeFile\cmake-3.15. 0-rc1-win64-x64\doc\cmake\html\_sources\variable\CMAKE_HOST_SYSTEM_NAME.rst.txt
D:\\CodeFile\cmake-3.15. 0-rc1-win64-x64\doc\cmake\html\_sources\variable\CMAKE_HOST_SYSTEM_PROCESSOR.rst.txt
D:\\CodeFile\cmake-3.15. 0-rc1-win64-x64\doc\cmake\html\_sources\variable\CMAKE_HOST_SYSTEM_VERSION.rst.txt
Copy the code

So we’re done iterating.

Move files

To move a file, we simply call os.renames as follows:

import os
os.renames(".\\test\\1.jpg"."1.jpg")
Copy the code

The effect of the above code is to move the 1.jpg image from the test directory in the current directory to the current directory. Or we could use absolute paths:

import os
os.renames(r"D:\test1\a2.jpeg".r"D:\a1.jpeg")
Copy the code

So we can move the file. And we organize the operation of the file is to move the file according to certain rules.

Four, automatic file sorting

The operation of organizing pictures is varied and different for different people. So this is just some of the cleanup operations that might be required.

1. Store the pictures in a centralized manner

Sometimes we might want to put the image set in a directory, or we might want to put the image set in a directory with the specified name (for example, QQ images are named IMG_… , we can use this to organize all QQ pictures). At this point we can finish up with today’s lecture.

import os
todir = "D:\imgs"
basedir = r"D:\\"
If the directory does not exist, create it
if not os.path.exists(todir):
    os.mkdir(todir)
img_name = 1000
for root, dirs, files in os.walk(basedir):
    for file in files:
        path = os.path.join(root, file)
        if path.endswith(".jpg") :# move file
            os.renames(path, "D:\\imgs\\" + str(img_name) + ".jpg")
            img_name += 1
Copy the code

Here we implement the operation of collating all JPG files to the specified directory. But sometimes moving files can be dangerous, so we can also choose not to move files and copy them:

import os
todir = "D:\\imgs"
basedir = r"D:\\"
If the directory does not exist, create it
if not os.path.exists(todir):
    os.mkdir(todir)
img_name = 1000
for root, dirs, files in os.walk(basedir):
    for file in files:
        path = os.path.join(root, file)
        if path.endswith(".jpg") :# move file
            with open(path, "rb") as f1:
                with open("D:\\imgs\\" + str(img_name) + ".jpg"."wb") as f2:
                    content = f1.read()
                    f2.write(content)
            img_name += 1
Copy the code

So we can copy the file.

2. Synchronize files

We can also do some other sorting, just by adding some conditions to the traversal:

import os
todir = "D:\\imgs"
basedir = r"D:\\"
If the directory does not exist, create it
if not os.path.exists(todir):
    os.mkdir(todir)
img_name = 1000
for root, dirs, files in os.walk(basedir):
    for file in files:
        path = os.path.join(root, file)
        if path.endswith(".jpg") :# Organize images
        elif path.endswith(".txt") :# Organize text
        else:
            pass
Copy the code

So that we can organize the documents in our own way.

3. Obtain file properties

Other file defilement operations are not mentioned here. Let’s talk about obtaining file properties. The code is as follows:

import os
stat = os.stat("test1/a3.jpeg")
print(stat)
Copy the code

We can view the properties of the file with the following output:

os.stat_result(st_mode=33206, st_ino=281474977264692, st_dev=275139486, st_nlink=1, st_uid=0, st_gid=0, st_size=95289, st_atime=1632752119, st_mtime=1586520880, st_ctime=1632664508)
Copy the code

This includes file mode, file size, creation time, modification time, etc. That way we can organize the files more accurately once we get the information. For example, we can sort out the files we changed in the last day, so that we can find the files we want to use.