从文件制作文件夹

2024-04-24 03:42:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我的文件就是这样的。。你知道吗

   a-b-2013-02-12-16-38-54-a.png
   a-b-2013-02-12-16-38-54-b.png

我喜欢上千个这样的文件。 我们可以为每一组文件创建文件夹吗,比如a-b 我能说吗?我该怎么做?你知道吗

import glob, itertools, os
import re
foo = glob.glob('*.png')

for a in range(len(foo)):
        print foo[a]
        match=re.match("[a-zA-Z0-9] - [a-zA-Z0-9] - *",foo[a])
        print "match",match

那么,这里的错误是什么?你知道吗


Tags: 文件inimportre文件夹forfoopng
3条回答

glob.glob('*.png')列出所有文件。你知道吗

然后可以使用regex(import re)解析每个文件名。你知道吗

使用os.mkdir(path)生成目录。你知道吗

使用os.rename(src, dst)移动文件。你知道吗

此代码适用于您要执行的操作:

import os

path="./"
my_list = os.listdir(path)   #lists all the files & folders in the path ./ (i.e. the current path)

for my_file in my_list:
    if ".png" in my_file:
        its_folder="something..."
        if not os.path.isdir(its_folder):
            os.mkdir(its_folder)     #creates a new folder
        os.rename('./'+my_file, './'+its_folder+'/'+my_file)    #moves a file to the folder some_folder.

您必须为要创建的每个文件夹指定名称,并将文件移到其中(而不是“something…”),例如:

its_folder=my_file[0:3];    #if my_file is "a-b-2013-02-12-16-38-54-a.png" the corresponding folder would have its first 3 characters: "a-b".

让你目不转睛,适应自己需要的东西:

让我们创建一些文件:

$ touch a-b-2013-02-12-16-38-54-{a..f}.png


$ ls
a-b-2013-02-12-16-38-54-a.png  a-b-2013-02-12-16-38-54-c.png  a-b-2013-02-12-16-38-54-e.png  f.py
a-b-2013-02-12-16-38-54-b.png  a-b-2013-02-12-16-38-54-d.png  a-b-2013-02-12-16-38-54-f.png

一些Python

#!/usr/bin/env python

import glob, os

files = glob.glob('*.png')

for f in files:
    # get the character before the dot
    d = f.split('-')[-1][0]
    #create directory
    try:
        os.mkdir(d)
    except OSError as e:
        print 'unable to creade dir', d, e
    #move file
    try:
        os.rename(f, os.path.join(d, f))
    except OSError as e:
        print 'unable to move file', f, e

我们开始吧

$ ./f.py

$ ls -R
.:
a  b  c  d  e  f  f.py

./a:
a-b-2013-02-12-16-38-54-a.png

./b:
a-b-2013-02-12-16-38-54-b.png

./c:
a-b-2013-02-12-16-38-54-c.png

./d:
a-b-2013-02-12-16-38-54-d.png

./e:
a-b-2013-02-12-16-38-54-e.png

./f:
a-b-2013-02-12-16-38-54-f.png

相关问题 更多 >