gpt4 book ai didi

python - 如何根据包含相同文件的目录结构重新排列文件?

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:11 27 4
gpt4 key购买 nike

我正在将计算机中的文件备份/同步到外部硬盘。

例如,我像这样对外部硬盘中的一些文件进行了排序(我有大约 1000 个目录和 10000 个文件,下面给出的目录结构仅供说明之用)

folderA
-aa.jpg
-ab.mp3
-ac.mp4

folderB
-ba.jpg
-bb.mp3
-bc.mp4

在我的计算机中,“temp”文件夹中有相同的文件

aa.jpg, ab.mp3, ac.mp4, ba.jpg, bb.mp3, bc.mp4

我在哪里

我希望“temp”中的文件像这样排列

temp

--folderA
-aa.jpg
-ab.mp3
-ac.mp4

--folderB
-ba.jpg
-bb.mp3
-bc.mp4

是否有任何工具或脚本可以为我执行此操作(针对 1000 多个目录和 10000 多个文件)?

最佳答案

对于 Windows,创建以下 python 脚本并将其复制到临时目录,只需将路径替换为您的“temp”:

import os
import shutil

if not os.path.exists('C:/Users/myuser/Desktop/day/folderA'):
os.makedirs('C:/Users/myuser/Desktop/day/folderA')
if not os.path.exists('C:/Users/myuser/Desktop/day/folderB'):
os.makedirs('C:/Users/myuser/Desktop/day/folderB')

sourcepath='C:/Users/myuser/Desktop/day'
source = os.listdir(sourcepath)
destinationpath = 'C:/Users/myuser/Desktop/day/folderA'
destinationpath2 = 'C:/Users/myuser/Desktop/day/folderB'
for files in source:
if files.startswith('a'):
shutil.move(os.path.join(sourcepath,files), os.path.join(destinationpath,files))
if files.startswith('b'):
shutil.move(os.path.join(sourcepath,files), os.path.join(destinationpath2,files))

listA = os.listdir('C:/Users/myuser/Desktop/day/folderA')
listA.sort()
listB = os.listdir('C:/Users/myuser/Desktop/day/folderB')
listB.sort()

关于python - 如何根据包含相同文件的目录结构重新排列文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44321052/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com