|
Example
Himself wrote a Python script file traversal of found files for specific treatment. Lacks technical content, but also recorded it.
Code Copy the code below
#! / 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 # Traversing File
for filename in filenames:
Absolute address thefile = os.path.join (dirpath, filename) # file
try:
if os.path.splitext (thefile) [1] == '. rpm': # filter .rpm file format
#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) # copy files to the wrong directory desdir
f = open ( 'list.txt', 'a') # error is written to the file list list.txt
f.write (filename + '')
f.close ()
except IOError, err:
print err
sys.exit ()
if __name__ == '__main__':
dir = Packages ( '/ mnt / cdrom', '/ mnt / erpm') # source directory is / mnt / cdrom, the target directory is / mnt / erpm
dir.check ()
Examples, traversing the directory file
Code Copy the code below
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
example
Traverse Folder and delete specific file format
Code Copy the code below
#! / 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) |
|
|
|