一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python中批量移动目录所有文件函数

时间:2014-07-17 编辑:简简单单 来源:一聚教程网

例子, 这个是配置文件做法,如果你不使用配置文件可以直接使用函数试的操作方法

 代码如下 复制代码

配置文件config.ini
[global]
#原文件存放目录
dir1=F:\work\python\3595\pyserver\test
#新文件存放目录
dir2=F:\work\python\3595\pyserver\test1

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os,ConfigParser,time
class file_openate(object):
    def __init__(self):
        #初如化读取数据库配置
        dir_config = ConfigParser.ConfigParser()
        file_config=open('config.ini',"rb")
        dir_config.readfp(file_config)
        self.dir1=str(dir_config.get("global","dir1"))
        self.dir2=str(dir_config.get("global","dir2"))
        self.dir2=unicode(self.dir2,'utf8')
        self.dir1=unicode(self.dir1,'utf8')
        #print self.dir2
        #self.dir2=self.dir2.unicode(os.path.join(os.path.dirname(__file__),'CtManage','templates').replace('\\','/'),"gb2312")
        file_config.close()

    #数据库连接
    def file_list(self):
        input_name_han="请输入需要移多少文件:".decode('utf-8')
        while 1:
              input_name=raw_input("number:")
              input_name=str(input_name)
              #print input_name
              if input_name.isdigit():
                  input_name=int(input_name)
                  i=0
                  for filename in os.listdir(self.dir1):
                      i=i+1
                      if i <= input_name:
                          os.rename(self.dir1+'/' +filename,self.dir2 +'/' +filename)
                          print filename+"成功".decode('utf-8')

              else:
                   print "请输入正确的数字".decode('utf-8')       
file_name=file_openate()
file_name.file_list()

例子,对于不喜欢使用配置文件操作的朋友可使用函数操作,如下也有一个相关的例子

 代码如下 复制代码

#encoding:utf-8
import os,sys
import shutil
from shutil import Error
from shutil import copystat
from shutil import copy2
def copy_file(src_file, dst_dir): 
    #声明函数 copy_file( 要复制的文件,目标目录,复制符号连接内容到新目录,没有要忽略文件)
   
    '''复制一个文件中所以的东西到另一个目录中'''
    if os.path.isfile(src_file):
        if os.path.isdir(dst_dir):      #dst目标存在时,就pass,不存在就创建
            pass
        else:
            os.makedirs(dst_dir)
   
        errors = []                             #声明 errors列
        print src_file
        srcname = src_file   
        filename = os.path.basename(src_file)
        dstname = os.path.join(dst_dir, filename)   #将路径名(dst)添加到文名(name)之前然后赋值给 dstcname
        from shutil import Error
        try:                                #尝试
            if os.path.isfile(srcname):        #如果srcname文件是存在
                copy2(srcname, dstname)
                print srcname,dstname,'success'
            elif os.path.isdir(dstname):          #目标文件存在,删除后,再复制新的
                os.remove(dstname)
                print 'remove %s' % dstname
                copy2(srcname, dstname)
           
        except (IOError, os.error), why:                #除(IOError[与文件有关的异常],操作系统异常)外,返回原因
            errors.append((srcname, dstname, str(why))) # 向errors列里添加,(要复制的目录,目标目录,错误原因)
        # catch the Error from the recursive jiecptree so that we can  从递归复制中捕捉这个错误,以便于我们能继续复制其他文件
        # continue with other files
        except Error, err:              #除错误外,返回错误:
            errors.extend(err.args[0])  #扩展 errors 列,添加(err.args[0] 元素)
           
           
        try:                                #尝试
            copystat(srcname, dstname)              # 从srcname表示的文件复制其权限位,上次访问时间,最后修改时间 到 dst,
        except WindowsError:                # 除 Windows错误 外:
            # can't copy file access times on Windows   在Windows上无法复制文件访问时间
            pass                            # 通过(不作任何处理)
        except OSError, why:                # 除 操作系统错误 外,返回原因:
            errors.extend((src_file, dst_dir, str(why))) #扩展 errors 列,添加(要复制的文件,目标目录,错误原因)
        if errors:                          # 如果错误
            raise Error(errors)             # 提示错误
    else:
        print 'the fisrt parm should be a file name'
   
   
if __name__ == '__main__':
    if len(sys.argv) != 3:
        print 'need srcFile and dstDir'
        sys.exit(-1)
    srcFile = sys.argv[1]
    dstDir = sys.argv[2]
    copy_file(srcFile, dstDir)

热门栏目