下午遇到一个需求需要把图片以后三位的数字为名字建目录并把图片放进去
总结了两种简单办法:1。写shell脚本
awk '{printf "mkdir -p %s\n",substr($1,11,3)}' dir.txt
awk '{printf "mv %s %s\n",$1,substr($1,11,3)}' dir.txt
用awk生成命令直接执行。
2。 就是用python写程序操作,结果是时间原因忘刚了。费了好大劲。现在把代码保存在这。
写道
'''
Created on May 28, 2010
@author: zuzu08
'''
import os
import shutil
import time
from os import listdir
from os.path import isdir
#source = ['/home/swaroop/byte', '/home/swaroop/bin']
source = '/home/www/img/1001'
target_dir = '/home/www/img'
now = time.strftime('%Y%m%d')
if isdir(source) != True:
print 'Error: source is not a directory'
exit()
k=0
filelist = listdir(source)
t = 0
for name in filelist :
if name.find('jpg') == -1 and name.find('png') == -1 and name.find('gif') == -1 and name.find('bmp') == -1 :
del(filelist[t])
t = t + 1
print(filelist)
#exit()
for name in filelist :
srcFilename = source + '/' + name
print(srcFilename)
srcFilename = '"' + srcFilename + '"'
nPos = name.index(".")
str1=name[nPos-3:nPos]
print(str1)
desdir=target_dir+'/'+str1 ;
print(desdir)
if isdir(desdir) != True:
os.mkdir(desdir)
desFilename = desdir + '/'+ name
desFilename = '"' + desFilename + '"'
shutil.copyfile(srcFilename,desFilename)
print "copy %s to %s successful" % (srcFilename,desFilename)
print 'total copy', k, 'files'
Created on May 28, 2010
@author: zuzu08
'''
import os
import shutil
import time
from os import listdir
from os.path import isdir
#source = ['/home/swaroop/byte', '/home/swaroop/bin']
source = '/home/www/img/1001'
target_dir = '/home/www/img'
now = time.strftime('%Y%m%d')
if isdir(source) != True:
print 'Error: source is not a directory'
exit()
k=0
filelist = listdir(source)
t = 0
for name in filelist :
if name.find('jpg') == -1 and name.find('png') == -1 and name.find('gif') == -1 and name.find('bmp') == -1 :
del(filelist[t])
t = t + 1
print(filelist)
#exit()
for name in filelist :
srcFilename = source + '/' + name
print(srcFilename)
srcFilename = '"' + srcFilename + '"'
nPos = name.index(".")
str1=name[nPos-3:nPos]
print(str1)
desdir=target_dir+'/'+str1 ;
print(desdir)
if isdir(desdir) != True:
os.mkdir(desdir)
desFilename = desdir + '/'+ name
desFilename = '"' + desFilename + '"'
shutil.copyfile(srcFilename,desFilename)
print "copy %s to %s successful" % (srcFilename,desFilename)
print 'total copy', k, 'files'