最近在学习python,用python做了个文件搬动的实现
#coding:utf-8
#-*-codding:cp936-*-
import os
import fnmatch
import shutil
import time
#.decode('utf-8').encode('gbk')是为了让raw_input中显示中文
file_suffix=raw_input("输入文件后缀,例如*.txt:".decode('utf-8').encode('gbk'))
source_file=raw_input("输入源文件目录:".decode('utf-8').encode('gbk'))
target_file=raw_input("输入目标文件目录:".decode('utf-8').encode('gbk'))
if os.path.exists(target_file) == False:
print 'The directory is not exist, It had make a new %s' % target_file
os.makedirs(target_file)
record="record.txt"
file_record=os.path.join(target_file,record)
f_handle=open(file_record,'a')
#利用os.walk遍历该文件目录下所有的目录和文件,通过os.path.join(rt,f)得到目标文件的路径,rt是起始路径,dirs是起始路径下的文件夹(列表),files是起始路径下的文件(列表)
def copy_file_to_targetDir(source_file):
file_num=0
for rt,dirs,files in os.walk(source_file):
for f in files:
if fnmatch.fnmatch(f,file_suffix):
file_dir=os.path.join(rt,f)
f_handle.write(file_dir + '\n')
file_num+=1
print file_dir
shutil.copy(file_dir,target_file)
print "\nIt totally find %d matched files" % file_num
print "\nAll the file directory had been saved in record.txt"
time.sleep(3)
copy_file_to_targetDir(source_file)
f_handle.close()