位置:首页 > 网络编程 > Python
python 遍历文件脚本的简单示例
日期:2023-01-06 人气:

大家好,对python 遍历文件脚本的简单示例感兴趣的小伙伴,下面一起跟随三零脚本的小编来看看python 遍历文件脚本的简单示例的例子吧。

自己写的一个Python遍历文件脚本,对查到的文件进行特定的处理。没啥技术含量,但是也记录一下吧。

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import shutil
dir = "/mnt/Packages"
class Packages:
    def __init__(self,srcdir,desdir):
        self.sdir=srcdir
        self.ddir=desdir
    def check(self):
        print('program start...')
        for dirpath, dirnames, filenames in os.walk(self.sdir):   #遍历文件
            for filename in filenames:
                thefile=os.path.join(dirpath,filename)            #文件的绝对地址
                try:
                    if os.path.splitext(thefile)[1]=='.rpm':      #筛选.rpm格式的文件
                        #print('Fount rpm package: ' + thefile)
                        if 'inspuer' in os.popen('rpm -qpi ' + thefile).read().rstrip():
                            print('Found error package: ' + thefile)
                            shutil.copy(thefile, self.ddir)  #将错误文件复制到desdir目录
                            f = open('list.txt', 'a')    #将错误文件列表写入到list.txt
                            f.write(filename + '\n')
                            f.close()
                except IOError, err:
                    print err
                    sys.exit()

if __name__ == '__main__':
    dir=Packages('/mnt/cdrom','/mnt/erpm')   #源目录为/mnt/cdrom,目标目录为/mnt/erpm
    dir.check()