Py&禅

博客园 首页 新随笔 联系 订阅 管理

os.path 包含有能处理长文件名和路径名的函数, 使用的时候import os

   

1.对文件名的操作

1>

import os

filename = "c:\\qtest\\Winter.jpg"

print "using", os.name, "..."

print "split", "=>", os.path.split(filename)

print "splitext", "=>", os.path.splitext(filename)

print "dirname", "=>", os.path.dirname(filename)

print "basename", "=>", os.path.basename(filename)

print "join", "=>", os.path.join(os.path.dirname(filename), os.path.basename(filename))

   

2>

import os

FILES = (
os.curdir,
"/",
"file",
"/file",
"samples",
"samples/sample.jpg",
"directory/file",
"../directory/file",
"/directory/file"
)

for file in FILES:
  print file, "=>",
if os.path.exists(file): #
返回true file及路径存在
  print "EXISTS",
if os.path.isabs(file): #
返回true 如果是绝对路径
  print "ISABS",
if os.path.isdir(file): #
返回true 当是路径时
  print "ISDIR",
if os.path.isfile(file): #
返回true 当是file
  print "ISFILE",
if os.path.islink(file): #
返回true 当是符号链接时
  print "ISLINK",
if os.path.ismount(file): #return true when the file is a mount point
  print "ISMOUNT",
print

2. walk 函数查找在目录树中的所有文件

import os

def callback(arg, directory, files):
for file in files:
  print os.path.join(directory, file), repr(arg)

os.path.walk(".", callback, "secret message")

   

3.同样的, os.listdir也可以实现类似的文件遍历功能

   

import os

def index(directory):
  # like os.listdir, but traverses directory trees
  stack = [directory]
  files = []
  while stack:
    directory = stack.pop()
    for file in os.listdir(directory):
      fullname = os.path.join(directory, file)
      files.append(fullname)
    if os.path.isdir(fullname) and not os.path.islink(fullname):
      stack.append(fullname)
  return files

for file in index("."):
print file

   

4. 构造一个类来实现以上功能

   

import os

   

class DirectoryWalker:
# a forward iterator that traverses a directory tree

def __init__(self, directory):
self.stack = [directory]
self.files = []
self.index = 0

def __getitem__(self, index):
  while 1:
  try:
    file = self.files[self.index]
    self.index = self.index + 1
  except IndexError:
    # pop next directory from stack
    self.directory = self.stack.pop()
    self.files = os.listdir(self.directory)
    self.index = 0
  else:
    # got a filename
    fullname = os.path.join(self.directory, file)
    if os.path.isdir(fullname) and not os.path.islink(fullname):
      self.stack.append(fullname)
    return fullname

for file in DirectoryWalker("."):
  print file

posted on 2010-05-10 21:22  Py&禅  阅读(2671)  评论(0)    收藏  举报