python拷贝文件|python 怎么实现两台服务器上批量复制文件

A. python 中如何实现对文件的复制、粘贴

用shutil模块#!/usr/bin/env python#-*- coding: utf-8 -*-import osimport os.pathfrom shutil import dest_dir = ur'd:\新建文件专夹属'if not os.path.isdir(dest_dir): os.makedirs(dest_dir)file_path = ur'c:\123\1.txt'(file_path, dest_dir)

B. 用python把文件夹下的所有文件包括文件夹里面的文件都拷贝到同一个目录下

importosimportshutildefwenjian(path):ifos.path.isfile(path):shutil.(path,'c:\new_dir')ifos.path.isdir(path):lists=os.listdir(path)foriinlists:wenjian(i)foriinos.walk('c:\1'):wenjian(i)

建议你把检索到的文件都放到一个新的文件夹里,要不然系统在同一个文件夹里不停版的读权取和写入可能会陷入死循环以至出错。

C. python中怎样将文件拷贝到指定的目录下

importshutilshutil.(sourceDir,targetDir)

D. python 怎么实现两台服务器上批量复制文件

1、把excel里文件名那一列复制,粘进一个空白的文本文件,命名为filelist.txt,上传到服务器。2、在服务器上使用脚本导出,python脚本 fileCp.py 。代码示例:#! python #coding:utf-8 ##!/usr/bin/python # Filename : fileCp.py import sys import os import shutil fileList='filelist.txt' targetDir='files' filedir = open(fileList) line = filedir.readline() log = open('running.log','w') while line: line = line.strip('\n'); basename = os.path.basename(line) exists = os.path.exists(line) if exists : print ' '+line+' to '+os.getcwd()+'/'+targetDir+'/'+basename log.write(' '+line+' to '+os.getcwd()+'/'+targetDir+'/'+basename+'\r\n') shutil.(line,targetDir+'/'+basename) else: print line+' not exists' log.write(line+' not exists'+'\r\n') line = filedir.readline() log.close()

E. python中怎样将文件拷贝到指定的目录下

代码:import osimport shutilfrom shutil import Errorfrom shutil import statfrom shutil import 2src = "" #需要复制的文件目录dst = "" #目标目录def jiecptree(src, dst, symlinks=False, ignore=None): #声明函数 ree( 要复制的目录,目标目录,复制符号连接内容到新目录,没有要忽略文件) names = os.listdir(src) #获得要复制目录的文件名列表,赋给变量 names if ignore is not None: #如果 ignore 不是None值 ignored_names = ignore(src, names) # src目录中要忽略文件的名字赋给 ignored_names else: # 否则 ignored_names = set() #ignore_name 被 不重复空元素集 赋值 if os.path.isdir(dst): pass else: os.makedirs(dst)# print"dstfirst:"+dst errors = [] #声明 errors列 for name in names: #将names里的元素循环复制给name if name in ignored_names: #如果name在要求被忽略的列里出现 continue #继续for循环(跳回for,从新循环下个元素) srcname = os.path.join(src, name) #将路径名(src)添加到文名(name)之前然后赋值给 srcname dstname = os.path.join(dst, name) #将路径名(dst)添加到文名(name)之前然后赋值给 dstcname from shutil import Error# print "name:"+name# print "src:"+src# print "dst:"+dst try: #尝试 if os.path.islink(srcname): continue elif os.path.isdir(srcname): #如果srcname路径是存在 jiecptree(srcname, dstname, symlinks, ignore) elif os.path.isdir(dstname): os.remove(dstname) 2(srcname, dstname) else: # 否则 2(srcname, dstname) # 复制srcname到dstname# print "srcname:"+srcname# print "dstname:"+dstname # XXX What about devices, sockets etc.? #怎样装置 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: #尝试 stat(src, dst) # 从src复制权限位,上次访问时间,最后修改时间 到 dst, except WindowsError: # 除 Windows错误 外: # can't file access times on Windows 在Windows上无法复制文件访问时间 pass # 通过(不作任何处理) except OSError, why: # 除 操作系统错误 外,返回原因: errors.extend((src, dst, str(why))) #扩展 errors 列,添加(要复制的目录,目标目录,错误原因) if errors: # 如果错误 raise Error(errors) # 提示错误更多相关内容可参考资料http://www.viiboo.cn

F. python复制excel文件

# -*- coding: utf-8 -*-import xlrdimport shutilimport osdef read_excel(): # 打开文件 workbook = xlrd.open_workbook(r'C:\Users\xxx\Desktop\xxx.xls') # 获取所有sheet print (workbook.sheet_names()) # [u'sheet1', u'sheet2'] #获取sheet sheet= workbook.sheet_names()[0] sheet_data=workbook.sheet_by_name(sheet) print(sheet_data) # sheet的名称,行数,列数 print (sheet_data.name,sheet_data.nrows,sheet_data.ncols) rows = sheet_data.row_values(0) # 获取第四行内容 cols = sheet_data.col_values(2) # 获取第三列内容 print (rows) for i,j in enumerate(rows): print(i,':',j) for i in range(sheet_data.nrows): strr=sheet_data.row_values(i)[5][:5] if(strr == 'AXIAL'): dicom_path=sheet_data.row_values(i)[15] row_path=sheet_data.row_values(i)[16] print(row_path) roww=row_path.split('\\',3)[3] print(roww) #row_path='C:\Users\xxx\Desktop\xxx' path_now=os.path.join('\\\\xxx',roww) print(path_now) shutil.tree(path_now,r'C:\Users\xxx\Desktop\Get') #shutil.tree(row_path,r'C:\Users\xxx\Desktop') break if __name__ == '__main__': read_excel()#文件复制主要利用shutil包,tree的第一个参数为需要复制的文件夹,第二个参数为目标位置;但第二个参数的目标位置必须不存在,否则会报错。

G. python怎么拷贝文件夹下的文件

def upload_file(src_path, dst_path):# 目标目录是否存在,不存在则创建if not os.path.exists(os.path.dirname(dst_path)):os.makedirs(os.path.dirname(dst_path)) # 本地文件是否存在,存在则移动到目标目录下if os.path.exists(src_path):shutil.move(src_path, dst_path)

H. python对文件的独操作有哪几种请详细说明每种方法

1.打开文件:f=open(r'E:\PythonProjects\test7\a.txt',mode='rt',encoding='utf-8')以上三个单引号内分别表示:要打开的文件的路径,mode为文件打开方式具体介绍在下文,encoding为文件的字符编码,一般默认为utf-82.读写文件:data=f.read() # 读文件f.write() # 写文件3.关闭文件:f.close()4.为了简便,一般采用上下文的方法进行文件操作,可不用关闭文件with open('a.txt',mode='rt',encoding='utf-8') as f:data=f.read() print(data)with open('a.txt',mode='wt',encoding='utf-8') as f: f.write('hello world')5.控制文件读写的操作:r:(默认模式):只读:以该模式打开文件时,若文件不存在则报错,若文件存在,则文件指针在文件开头,即从文件开头开始读文件w:只写:以该模式打开文件时,若文件不存在则创建一个文件,如文件存在,则清空文件内容,文件指针移到开头a:追加写:以该模式打开文件时,若文件不存在则创建一个文件,如文件存在,则将文件指针移到文件末尾,在文件末尾写入新的内容6.控制文件读写内容的模式:(t 和 b都不能单独使用,必须与r,w,a结合使用)t:(默认):无论读写都是以字符为单位,只能识别文本文件,必须要制定encodingb:无论读写都是以字节为单位,可以识别所有文件,一定不能指定encoding7.文件的拷贝with open ('a.txt',mode='rb') as af,\ open('b.txt',mode='wb') as bf: data=af.read f.write(data)执行程序后,打开文件,即可发现文件已成功拷贝,这里使用 b 而不是用 t 模式,是因为文件有多种格式8.文件的修改:文件的修改是在硬盘上实现文件的覆盖,相当于一个新的文件以旧的文件名来命名的; 文件的修改有俩种方式,分别适用于不同的情景方式一(适用于容量小的文件):这种方式的原理是:创建一个新的文件,将旧文件的内容拷贝到新的文件中;这样内存里就存在俩个文件,故不适用于容量大的文件,具体代码见下方 Viewwith open('a.txt',mode='rt',encoding='utf-8') as f: data=f.read() data_new=data.replace('yang', 'yv')with open('b.txt',mode='wt',encoding='utf-8')as p: p.write(data_new)方式二(适用于容量大的文件):此方式的原理为:读取旧文件的一行内容,修改后写到临时文件中,循环往复直到写完,然后将源文件删除,将临时文件命名为源文件名.这种方式在内存中只存在2行文件,节省内存,可用于大文件import oswith open('b.txt',mode='rt',encoding='utf-8') as f,\ open('.b.txt.swap',mode='wt',encoding='utf-8') as p: for line in f: p.write(line.replace('yv','yang')) # 调用replace方法,将源文件中的'yv',换成'yang'os.remove('b.txt')os.rename('.b.txt.swap','b.txt')9. 文件的阶段:truncate(n)将文件中n个字节后内容全删了,当 n 不存在时,即删除文件全部内容10.文件内指针的移动f.seek(): 指针的移动是以字节为单位的seek 有三种模式:0:(默认模式) 指针在文件开头,只有在 0 模式可以在 t 模式下用,也可以在 b 模式下用,而 1 ,2 模式只能在 b 模式下使用1:指针在当前位置2:指针在文件末尾以下为具体事例:# 0with open('a.txt',mode='rt',encoding='utf-8')as f: f.seek(3,0) print(f.tell()) # 指针当前位置 print(f.read()) # 从指针后读出所有内容 # 1 参照指针当前位置 with open('a.txt',mode='rb')as f: f.read(2) f.seek(4,1) print(f.tell()) print(f.read().decode('utf-8')) # 2 参照文件末尾 with open('a.txt',mode='rb')as f: f.seek(-5,2) print(f.tell()) print(f.read().decode('utf-8'))当 seek处于 2 模式时,可以将文件中新加入的内容打印出来,具体代码如下:# 另一个文件进行写操作,写的代码如下: with open('a.txt',mode='at',encoding='utf-8')as f: f.write('hello world\n')# 每在文件中写入新的内容,都打印出来,以下代码执行打印操作:import timewith open('a.txt',mode='rb')as f: f.seek(0,2) while True: line=f.readline() # readline 可以读取没有内容的部分 # print(line.decode('utf-8')) if len(line)==0: time.sleep(0.1) else: print(line.decode('utf-8'))

I. python怎么实现文件的复制

给你看一段样例代码

defFile(src,des):srcFp=open(src,"r")desFp=open(des,"w")ch=srcFp.read(1)whilech!="":desFp.write(ch)ch=srcFp.read(1)srcFp.close()desFp.close()File("f:\new.txt","f:\test.txt")

J. python 复制文件

报错多半是这句targetDir = targetDir+'/'+os.path.split(sourceDir)[1]

你这句把本来的targetDir覆盖了,导致后面的文件的目标文件夹被修改

发个我写的吧,参考下吧

defFile(sourceDir,targetDir):ifnotos.path.exists(targetDir):os.makedirs(targetDir)forfilenameinos.listdir(sourceDir):path=os.path.join(sourceDir,filename)ifos.path.isdir(path):targetSubDir=os.path.join(targetDir,filename)File(path,targetSubDir)else:targetPath=os.path.join(targetDir,filename)open(targetPath,'wb').write(open(path,'rb').read())


赞 (0)