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): www.111cn.Net #遍历文件
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 + ' ')
f.close()
except IOError, err:
print err
sys.exit()
if __name__ == '__main__':
dir=Packages('/mnt/cdrom','/mnt/erpm') #源目录为/mnt/cdrom,目标目录为/mnt/erpm
dir.check()
例子,遍历目录下文件
代码如下 复制代码
def search(folder, filter, allfile):
folders = os.listdir(folder)
for name in folders:
curname = os.path.join(folder, name)
isfile = os.path.isfile(curname)
if isfile:
ext = os.path.splitext(curname)[1]
count = filter.count(ext)
if count>0:
cur = myfile()
cur.name = curname
allfile.append(cur)
else:
search(curname, filter, allfile)
return allfile
例子
遍历文件夹并删除特定格式文件
代码如下 复制代码
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
def del_files(path):
for root , dirs, files in os.walk(path):
for name in files:
if name.endswith(".tmp"):
os.remove(os.path.join(root, name))
print ("Delete File: " + os.path.join(root, name))
# test
if __name__ == "__main__":
path = '/tmp'
del_files(path)
相关文章
- 【Python成长之路】装逼的一行代码:快速共享文件【华为云分享】
- Python遍历路径下文件并转换成UTF-8编码
- Python 字符串_python 字符串截取_python 字符串替换_python 字符串连接
- Python+selenium自动化测试基础和元素定位
- 编码问题:python写入文件
- python-操作csv文件
- 如何用 Python 实现 Web 抓取?
- paip.判断文件是否存在uapi python php java c#
- Py之qrcode:调用python的qrcode库两种方式生成二维码、带logo的二维码
- Python:更改默认启动的python程序及其对应的安装包路径(更改pip的默认安装包的路径)图文教程之详细攻略
- Python编程语言学习:利用open函数将文本内容追加写入到txt文件中(两种方法实现)
- Python编程语言学习:一行代码利用enumerate函数把纯列表数据转为自带索引的字典数据,字典格式数据应用之key和value相互提取
- Python的IDE:基于Eclipse/MyEclipse软件的PyDev插件配置python的开发环境(不同python项目加载不同版本的python)—从而实现Python编程图文教程之详细攻略
- TF:基于tensorflow框架利用python脚本下将YoloV3训练好的.ckpt模型文件转换为推理时采用的.pb文件
- 100天精通Python(数据分析篇)——第59天:Pandas读写json文件(read_json、to_json参数说明+代码实战)
- 11.5K Star,一个开源的 Python 静态类型检查库
- python模块之sniffio
- 【Python实验】文件内容操作
- python读取写入csv文件
- Python爬虫:scrapy框架请求参数meta、headers、cookies一探究竟
- Python编程:读取pdf、pptx、docx、xlsx文件的页数
- Python中__init__()和self的有啥用
- python基础===Python性能优化的20条建议
- 【Leetcode刷题Python】198. 打家劫舍
- Python pip下载的whl文件到哪里了?如何找到并使用这些whl文件?(whl离线安装包的制作过程示例)
- 【Python】1.python 删除文件夹和文件
- Python .py 文件打包成 .exe 文件(Windows平台,python 3.x)