标签:文件操作 复制 删除
下面是把sourceDir文件夹下的以.JPG结尾的文件全部复制到targetDir文件夹下:
<span style="font-size:18px;">>>>import os
>>> import os.path
>>> import shutil
>>> def copyFiles(sourceDir,targetDir):
for files in os.listdir(sourceDir):
sourceFile = os.path.join(sourceDir,files) //把目录名和文件名链接起来
targetFile = os.path.join(targetDir,files)
if os.path.isfile(sourceFile) and sourceFile.find('.JPG')>0: //要求是文件且后缀是jpgshutil模块
拷贝目录

拷贝文件
拷贝文件的时候,如果指定的文件目的位置之间有目录不存在,则会抛出错误。所以最好在拷贝之间确认目录存在。

当目录存在的时候,拷贝文件就没有问题了。

删除目录使用如下函数:
shutil.rmtree(‘d:/dd‘)
移动文件或者文件夹到另外一个地方:
shutil.move(‘d:/c.png‘,‘e:/‘)
-------------------------------------------
那么存在一个问题就是,copy函数和copyfile函数二者的区别是什么呢?
看help:

从help中可以看出来,copyfile仅仅是把文件拷贝到目的文件。但是copy函数可以把文件的mode也一起拷贝。比如说原来的文件有+x可执行权限,那么目的文件也会有可执行权限。
删除一级目录下的所有文件:
<span style="font-size:18px;">def removeFileInFirstDir(targetDir):
for file in os.listdir(targetDir):
targetFile = os.path.join(targetDir, file)
if os.path.isfile(targetFile): //只删除文件不删除文件夹
os.remove(targetFile)</span><span style="font-size:18px;">def coverFiles(sourceDir, targetDir):
for file in os.listdir(sourceDir):
sourceFile = os.path.join(sourceDir, file)
targetFile = os.path.join(targetDir, file)
#cover the files //复写?
if os.path.isfile(sourceFile):
open(targetFile, "wb").write(open(sourceFile, "rb").read())</span><span style="font-size:18px;">def writeVersionInfo(targetDir):
open(targetDir, "wb").write("Revison:")</span>python之文件操作-复制、剪切、删除等,布布扣,bubuko.com
标签:文件操作 复制 删除
原文地址:http://blog.csdn.net/yapian8/article/details/30719643