Python quickly moves files in multiple folders to one folder

In daily office life, we often need to move files in multiple folders such as: (pictures png, jpg, jpeg, word documents, Excel, PPT, etc.), and we need to move the files in this folder to the same In the folder, if we copy and paste, it will be very cumbersome and waste a lot of time

I went through a certain degree, but I didn't find a suitable solution. The main thing is to let me download some messy software

Let's try it with Python today. First, I created a folder on my desktop. There are multiple folders inside the folder, and each folder has a file ( 每个文件夹内部的文件数量可能一个,可能多个,甚至是空的)

As shown in the picture:

Number of files inside each folder, more or less or none

insert image description here

The first step is to view all files in each folder

code:

import os
dir_path = r'd:\user\桌面\附件\\'
for f in os.listdir(dir_path):
    # print(f,end='')
    for f2 in os.listdir(dir_path+f):
        print(f'{
      
      f}{
      
      f2}',end='')
    print()

insert image description here

In the second step, move all files in each folder to the same folder ( 切记无法跨磁盘移动)

切记无法跨磁盘移动切记无法跨磁盘移动切记无法跨磁盘移动

So under the path where the attachment is stored, create a folder [after moving]

insert image description here

full code

import os
dir_path = 'd:\\user\\桌面\附件\\'
for f in os.listdir(dir_path):
    # print(f,end='')
    for f2 in os.listdir(dir_path+f):
        # print(f'{f},{f2}',end='')
        ori = dir_path+f+'\\'+f2
        now = r"d:\user\桌面\移动后\\" + f2
        os.rename(ori, now)
        print(f2,'移动成功')

insert image description here
insert image description here

I hope it can be helpful to everyone. If there is any mistake, please correct me.

A little programmer dedicated to office automation

Hope to get [a free follow] from everyone! grateful

Guess you like

Origin blog.csdn.net/weixin_42636075/article/details/131570712