zoukankan      html  css  js  c++  java
  • python之文件操作-复制、剪切、删除等

    以下是把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: //要求是文件且后缀是jpg

    shutil模块

    复制文件夹

    复制文件

    复制文件的时候。假设指定的文件目的位置之间有文件夹不存在。则会抛出错误。

    所以最好在拷贝之间确认文件夹存在。

    当文件夹存在的时候,复制文件就没有问题了。

    删除文件夹使用例如以下函数:

    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脚本进行文件的操作是非常方便的的。省却非常多时间

  • 相关阅读:
    [NOI2005]维护数列——Splay
    [Poi2000]病毒——补全AC自动机
    POJ1509 Glass Beads——SAM(后缀自动机)
    「NOI2011」阿狸的打字机——AC自动机+树状数组
    7.12Test——Graph Theory 1
    [BJWC2010]严格次小生成树
    7.09Test——DS1
    [SCOI2015]小凸想跑步——半平面交
    词频统计器(第三版)
    四则运算(测试)
  • 原文地址:https://www.cnblogs.com/blfbuaa/p/7027110.html
Copyright © 2011-2022 走看看