文件夹从文件
问题描述:
使这是我的文件看起来怎么样..文件夹从文件
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
那么,那里有什么错误?
答
列出所有带有glob.glob('*.png')
的文件。
然后,您可以使用正则表达式分析每个文件名(import re
)。
使用os.mkdir(path)
制作展架。
使用os.rename(src, dst)
移动文件。
+0
你可以看看我现在发布的代码吗? – pistal 2013-02-26 21:17:58
答
该代码会为你想做什么工作:
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.
你必须为你要创建的每个文件夹指定名称,以及文件移动到(而不是“东西... “),例如:
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
当然可以。执行适当的字符串操作并调用由Python包装的'mkdir'系统调用。 – 2013-02-26 20:17:37
你能指点我一个例子吗? – pistal 2013-02-26 20:18:47
http://docs.python.org/3/library/os.html?highlight=mkdir#os.mkdir&http://docs.python.org/3/library/string.html?highlight=string#string – 2013-02-26 20:21:42