zoukankan      html  css  js  c++  java
  • 吴裕雄--天生自然python学习笔记:python 文件批量处理

    Python 在文件处理方面表现突出,关于文件的处理
    也是很多人经常用到的功能。 对
    Python 的文件处理的技巧进行综合应用,比如把大量文件
    的复制、按指定的文件名进行保存、找出重复的照片、将
    所有的图片更改为相同大小等。
    除此之外,用户还可以利用 Python 程序来实现文件的
    查找功能。
    文件管理应用
    包括大量文件的
    复制、! 根据指定的名称保存文件、找出 重复照片、将所有的图片更改为相同的大小 。
    在日常生活中,我们也许还有过这样的体会:经常忘记以前创建的文件的保存
    位置,这也可以利用 Python 程序来解决。
    根据指定的编号保存文件
    首先用 os.walk 方法把批量的图片按指定的编号进行复制, os.walk 方法可以搜
    索指定目录及子目录下的所有文件。
    应用程序概述
    读取当前目录及子目录下的所有 jpg 文件,井复制到该目录下的 output2 目录,
    文件名以 pO.jpg 、 pl 扣g 的形式进行编号。

     

    import os,shutil
    
    cur_path=os.path.dirname(__file__) # 取得当前路径
    sample_tree=os.walk(cur_path)
    output_dir = 'output2'
    
    for dirname,subdir,files in sample_tree:
        allfiles=[]
        basename= os.path.basename(dirname)
        if basename == output_dir:  # output2 目录不再重复处理
            continue
    
        for file in files:  # 读取所有 jpg 文件名,存入 allfiles 列表中
            ext=file.split('.')[-1]
            if ext=="jpg": # 读取 *.jpg to allfiles
                allfiles.append(file)       
    
        if len(allfiles)>0: # 将 jpg 存入 output2 目录中
            target_dir = dirname + '/' + output_dir
            if not os.path.exists(target_dir):
                os.mkdir(target_dir)      
            counter=0
            for file in allfiles:  
                filename=file.split('.')[0] #取主文件名 
                ext=file.split('.')[1]      #取扩展文件名
                m_filename = "p" + str(counter)    #重新给主文件名进行编号命名
                destfile = "{}.{}".format(target_dir+'/'+m_filename, ext) # 加上完整路径
                srcfile=dirname + "/" + file
                print(destfile)
                shutil.copy(srcfile,destfile); # 复制文件
                counter +=1
    
    print("完成...")
    大批文件复制搬移及重新命名
    在计算机文件的操作中,常会有需要将大量的文件重新命名后再分别整理到指
    定的文件夹, Python 可以利用它特殊的文件处理能力,轻松地完成任务。
    应用程序总览
    在这个范例中,用户希望能对当前目录及子目录下的所有 mp3 文件进行处理,
    除了滤除不合法字符,再依新的命名原则更改档名后复制到 <output> 目 录中。
    将文件名中的不合法字符滤除,将新的合法文件名复制到<output> 目录 。

    import os,shutil
    
    output_dir = 'output'
    cur_path=os.path.dirname(__file__) # 取得目前路徑
    sample_tree=os.walk(cur_path)
    
    for dirname,subdir,files in sample_tree:
        allfiles=[]
        basename= os.path.basename(dirname)
        if basename == output_dir:  # output 目錄不再重複處理
            continue
       
        for file in files:  # 讀取所有 mp3 檔名,存入 allfiles 串列中
            ext=file.split('.')[-1]
            if ext=="mp3": # 讀取 *.mp3 to allfiles
                allfiles.append(file)
             
        if len(allfiles)>0: # 將 mp3 存入 output 目錄中
            target_dir = dirname + '/' + output_dir
            if not os.path.exists(target_dir):
                os.mkdir(target_dir)
      
            for file in allfiles:
                filename=file.split('.')[0] #主檔名         
                m_filename =""
                for c in filename: # 將主檔名中不合法的字元去除
                    if c==" " or c=="." or c=="," or c=="" or c=="" or c=="(" or c==")":
                        m_filename += ""  # 去除不合法字元
                    else:
                        m_filename += c   
    
            destfile = "{}.{}".format(target_dir+'/'+m_filename, ext) # 加上完整路徑
            srcfile=dirname + "/" + file
            print(destfile)
            shutil.copy(srcfile,destfile); # 複製檔案
                
    print("完成...")
    找出重复的照片
    电脑中的照片经过复制及移动,难免有些名称相同的照片,但内容可能不一样 。
    利用 hashlib.md5 ()可以轻松比较两张照片是否相同。
    应用程序概括
    读取当前目录及子目录下的所有 png 和 jpg 文件,比较重复的照片 。

    import os,hashlib
    
    cur_path=os.path.dirname(__file__) # 取得目前路径
    sample_tree=os.walk(cur_path)
    
    allmd5s = dict() 
    n=0
    for dirname,subdir,files in sample_tree:
        allfiles=[]   
        for file in files:  # 取得所有 .png .jpg 文件,存入 allfiles 列表中
            ext=file.split('.')[-1]
            if ext=="png" or ext=="jpg": 
                allfiles.append(dirname +'/'+file)       
             
        if len(allfiles)>0: 
            for imagefile in allfiles:
                img_md5 = hashlib.md5(open(imagefile,'rb').read()).digest()          
                if img_md5 in allmd5s:
                    if n==0:
                        print("找到下列重复的文件:")
                        n+=1
                    print(os.path.abspath(imagefile))
                    print(allmd5s[img_md5] + "
    ")
                else:
                    allmd5s[img_md5] = os.path.abspath(imagefile) 

    print("完成...")
    把图片文件改为相同大小
    制作网页或往网站传输图片时,很多时候会要求规定大小的图片,遇到这种情
    况,如果只有少量文件,手动改一下图片尺寸就可以了;但如果需要调整大小的图
    片量非常多,我们就可以用 Python 来进行自动处理。
    更改图片大小的操作必须要用 Image 对象,所以首先要导入 Image 包 :

    导入之后就可通过 Image.op en (fi l e)来建立编辑该照片的 Image 对象,再通过该
    对象的方法来更改照片大小。
    例如 : 创建 Image 对象 img ,先以 size 属性取得照片的宽和高,再用 res i ze ()方
    法调整其宽度和高度,然后用 save ()方法进行保存,最后用 close()方法关闭对象。

    应用程序总览
    读取当前目录及子目录下的所有 png 和 jpg 文件,把照片宽度设为 800pixe l ,高
    度按比例调整,并把新的文件复制到 resized_photo 目 录下。

    import os
    from PIL import Image
    
    image_dir = 'resized_photo'
    image_width = 800
    
    cur_path=os.path.dirname(__file__) # 取得当前路径
    sample_tree=os.walk(cur_path)
    
    for dirname,subdir,files in sample_tree:
        allfiles=[] 
        basename= os.path.basename(dirname)
        if basename == image_dir:  # resized_photo 目录不再重复处理
            continue  
        for file in files:  # 取得所有 .png .jpg 文件,存入 allfiles 列表中
            ext=file.split('.')[-1]
            if ext=="png" or ext=="jpg":
                allfiles.append(dirname +'/'+file)
             
        if len(allfiles)>0: 
            target_dir = dirname + '/' + image_dir
            if not os.path.exists(target_dir):
                os.mkdir(target_dir)
            for file in allfiles:
                pathname,filename = os.path.split(file)
                img = Image.open(file)
                w,h = img.size
                img = img.resize((image_width,int(image_width/float(w)*h)))
                img.save(target_dir+'/'+filename)
                print("<{}> 复制完成!".format(target_dir+'/'+filename))
                img.close()
                
    print("完成...")  
  • 相关阅读:
    【一天一道兼容性】之——IE6下fixed失效
    【前端重构技能天赋】(三)——最终篇
    Putty中文乱码问题
    Cygwin Application initialization failed: no display name and no $DISPLAY environment
    c++中的string用法(二)
    在win7下面使用cygwin,并且安装使用git,以及git简明教程
    vi 一些命令(备忘,自己用的)
    对C++中string类型的总结
    ofstream和ifstream详细用法
    写第一个shell脚本,遇到的问题总结整理。
  • 原文地址:https://www.cnblogs.com/tszr/p/12035168.html
Copyright © 2011-2022 走看看