python怎么批量移动文件_python中批量移动目录所有文件函数
#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)
總結
以上是生活随笔為你收集整理的python怎么批量移动文件_python中批量移动目录所有文件函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python collection co
- 下一篇: python自动操作excel_Pyth