Skip to content

Instantly share code, notes, and snippets.

@singlepig
Created April 17, 2014 07:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save singlepig/10962162 to your computer and use it in GitHub Desktop.
Save singlepig/10962162 to your computer and use it in GitHub Desktop.
按文件名前缀分类文件。 一个目录下有很多形如2012-08-23 18.20.41.jpg的文件,要将这些文件进行分类,对于2012-08-23 18.20.41.jpg文件, 生成文件夹2012-08 ,将其放到文件夹内。
#!/usr/bin/env python
# encoding: utf-8
'''
按文件名前缀分类文件。
一个目录下有很多形如2012-08-23 18.20.41.jpg的文件,要将这些文件进行分类,对于2012-08-23 18.20.41.jpg文件,
生成文件夹2012-08 ,将其放到文件夹内。
'''
import sys
import os
def creatDir(names):
'''
根据目录下的文件名创建所需要的文件夹,已经存在的文件夹跳过。
'''
dirList = []
for name in names:
if os.path.isdir(name):
print ("%s is a dir." % (name) )
continue
dirList.append(name[0:7])
dirList = list(set(dirList))
print ( "将要创建的文件夹为:%s" % dirList)
print ( "将在 %s 下创建。" % absTargetPath )
os.chdir(absTargetPath)
for path in dirList:
if os.path.exists(path):
print ( "文件夹 %s 已经存在!" % path )
else:
os.makedirs(path)
print ( "创建文件夹 %s 成功!" % path)
def classify(names):
'''
将文件放到对应的文件夹中
'''
for n in xrange(len(nameList)):
old = os.path.join(absTargetPath, nameList[n])
new = os.path.join(absTargetPath, nameList[n][0:7])
'''
移动文件
'''
os.rename(old, new + '/' + nameList[n])
print ("文件 %s 移动到 %s 中,done!" % (nameList[n], new))
if __name__ == '__main__':
docPath = sys.argv[1]
print '需要进行分类的目标目录绝对路径为:'
absTargetPath = os.path.abspath(docPath)
print absTargetPath
nameList = []
for name in os.listdir(absTargetPath):
if os.path.isfile(absTargetPath + '/' + name):
nameList.append(name)
print ("包含文件 %s 个。" % len(nameList))
creatDir(nameList)
classify(nameList)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment