歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python遍歷目錄文件腳本的示例

Python遍歷目錄文件腳本的示例

日期:2017/3/1 9:19:50   编辑:Linux編程

例子

自己寫的一個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.1linuxidc.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的文章您也可能喜歡,不妨看看:

Linux下Python的安裝以及注意事項 http://www.linuxidc.com/Linux/2015-11/124861.htm

Ubuntu 14.04 下安裝使用Python rq模塊 http://www.linuxidc.com/Linux/2015-08/122441.htm

無需操作系統直接運行 Python 代碼 http://www.linuxidc.com/Linux/2015-05/117357.htm

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved