Bulk move directory All file functions in Python

Source: Internet
Author: User
Tags extend join in python

Example, this is the configuration file practice, if you do not use the configuration file can directly use the function of the Operation method

The code is as follows Copy Code

Configuration file 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= "Please enter how many files you want to move:". 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+ "Success". Decode (' Utf-8 ')

Else
Print "Please enter the correct number". Decode (' Utf-8 ')
File_name=file_openate ()
File_name.file_list ()

example, for friends who do not like to use a profile operation, you can use a function operation, as follows a related example

The code is as follows Copy Code

#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 (Files to be copied, target directories, copy symbols to a new directory, no files to ignore)

"Copy the contents of a file so that it is in another directory."
If Os.path.isfile (src_file):
If Os.path.isdir (dst_dir): #dst目标存在时, on pass, does not exist on the Create
Pass
Else
Os.makedirs (Dst_dir)

Errors = [] #声明 errors Column
Print Src_file
SrcName = Src_file
filename = Os.path.basename (src_file)
DstName = Os.path.join (dst_dir, filename) #将路径名 (DST) is added before Wennan (name) and then assigned to Dstcname
From Shutil import Error
Try: #尝试
If Os.path.isfile (srcname): #如果srcname文件是存在
Copy2 (SrcName, DstName)
Print Srcname,dstname, ' success '
Elif Os.path.isdir (dstname): #目标文件存在, delete, and then copy the new
Os.remove (DstName)
print ' remove%s '% DstName
Copy2 (SrcName, DstName)

Except (IOError, Os.error), Why: #除 (ioerror[file-related exceptions], operating system exceptions), return reason
Errors.append ((SrcName, DstName, str (why)) # Add to Errors column (directory to replicate, destination directory, error reason)
# Catch the error from the ' recursive jiecptree so we can capture this bug from recursive replication so we could continue to copy other files
# Continue with other files
Except error, err: #除错误外, returning errors:
Errors.extend (err.args[0]) #扩展 errors column, adding (err.args[0] Element)


Try: #尝试
Copystat (SrcName, DstName) # copies its permission bits from the file represented by SrcName, last access time, last modified time to DST,
Except Windowserror: # In addition to Windows errors:
# can ' t copy file access time on Windows cannot copy files on Windows
Pass # through (without any processing)
Except OSError, why: # reason to return except operating system error:
Errors.extend ((Src_file, Dst_dir, str (why)) #扩展 errors column, add (file to copy, target directory, error reason)
If errors: # if the error
Raise error (Errors) # Prompts for 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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.