简体   繁体   English

使用glob和os将文件放入文件夹并重命名?

[英]Using glob and os to put files into folders & rename?

I have a huge folder what contains about 5000 files with names similar to: 我有一个很大的文件夹,其中包含大约5000个文件,它们的名称类似于:

Rop OE[1932].exo
Make Dat[1932].edd
Back W'E[1934].exl
Pack Trees Pop[1944].exl
R.P END[1962].exl
Original CL0[1998].exp

I want it to create folders for all of these files with the name from the file above (without the extension) as seen below 我希望它为所有这些文件创建文件夹 ,其名称与上面文件的名称相同(不带扩展名),如下所示

Rop OE[1932]
Make Dat[1932]
Back W'E[1934]
Pack Trees Pop[1944]
R.P END[1962]
Original CL0[1998]

Then rename all of the files to remove the what appears to be a year so they appear as below 然后重命名所有文件以删除似乎是一年的文件 ,因此它们如下所示

Rop OE.exo
Make Dat.edd
Back W'E.exl
Pack Trees Pop.exl
R.P END.exl
Original CL0.exp

And then all of the files to be put in their associating folder (same name) 然后将所有文件放入其关联文件夹(相同名称)

What's the best way to do this, I've attempted to use glob to get the list and cycle through them all but it didn't seem to work correct. 最好的方法是什么,我尝试使用glob来获取列表并遍历所有列表,但似乎无法正常工作。

Use the glob , os , shutil and re libs: 使用globosshutilre libs:

import glob
import shutil
import os
import re

root = 'path/to/folder/*'

for f in glob.glob(root):
    dirname = f.rsplit('.')[0]
    os.mkdir(dirname)
    filename = os.path.split(re.sub(r'\[\d+\]', '', f))[-1]
    shutil.move(f, os.path.join(dirname, filename))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM