== os.path 模块 ==

``os.path`` 模块包含了各种处理长文件名(路径名)的函数. 先导入 (import) ``os``
模块, 然后就可以以 ``os.path`` 访问该模块. === 处理文件名=== ``os.path`` 模块包含了许多与平台无关的处理长文件名的函数.
也就是说, 你不需要处理前后斜杠, 冒号等. 我们可以看看 [Example 1-42 #eg-1-42] 中的样例代码. ====Example 1-42. 使用 os.path 模块处理文件名====[eg-1-42] ```
File: os-path-example-1.py import os filename = "my/little/pony" 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)) *B*using nt ...
split => ('my/little', 'pony')
splitext => ('my/little/pony', '')
dirname => my/little
basename => pony
join => my/little\pony*b*
``` 注意这里的 ``split`` 只分割出最后一项(不带斜杠). ``os.path`` 模块中还有许多函数允许你简单快速地获知文件名的一些特征,如 [Example 1-43 #eg-1-43] 所示。 ====Example 1-43. 使用 os.path 模块检查文件名的特征====[eg-1-43] ```
File: os-path-example-2.py 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):
print "EXISTS",
if os.path.isabs(file):
print "ISABS",
if os.path.isdir(file):
print "ISDIR",
if os.path.isfile(file):
print "ISFILE",
if os.path.islink(file):
print "ISLINK",
if os.path.ismount(file):
print "ISMOUNT",
print *B*. => EXISTS ISDIR
/ => EXISTS ISABS ISDIR ISMOUNT
file =>
/file => ISABS
samples => EXISTS ISDIR
samples/sample.jpg => EXISTS ISFILE
directory/file =>
../directory/file =>
/directory/file => ISABS*b*
``` ``expanduser`` 函数以与大部分Unix shell相同的方式处理用户名快捷符号(~,
不过在 Windows 下工作不正常), 如 [Example 1-44 #eg-1-44] 所示. ====Example 1-44. 使用 os.path 模块将用户名插入到文件名====[eg-1-44] ```
File: os-path-expanduser-example-1.py import os print os.path.expanduser("~/.pythonrc") # /home/effbot/.pythonrc
``` ``expandvars`` 函数将文件名中的环境变量替换为对应值, 如 [Example 1-45 #eg-1-45] 所示. ====Example 1-45. 使用 os.path 替换文件名中的环境变量====[eg-1-45] ```
File: os-path-expandvars-example-1.py import os os.environ["USER"] = "user" print os.path.expandvars("/home/$USER/config")
print os.path.expandvars("$USER/folders") *B*/home/user/config
user/folders*b*
``` === 搜索文件系统=== ``walk`` 函数会帮你找出一个目录树下的所有文件 (如 [Example 1-46 #eg-1-46]
所示). 它的参数依次是目录名, 回调函数, 以及传递给回调函数的数据对象. ====Example 1-46. 使用 os.path 搜索文件系统====[eg-1-46] ```
File: os-path-walk-example-1.py 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") *B*./aifc-example-1.py 'secret message'
./anydbm-example-1.py 'secret message'
./array-example-1.py 'secret message'
...
./samples 'secret message'
./samples/sample.jpg 'secret message'
./samples/sample.txt 'secret message'
./samples/sample.zip 'secret message'
./samples/articles 'secret message'
./samples/articles/article-1.txt 'secret message'
./samples/articles/article-2.txt 'secret message'
...*b*
``` ``walk`` 函数的接口多少有点晦涩 (也许只是对我个人而言, 我总是记不住参数的顺序).
[Example 1-47 #eg-1-47] 中展示的 ``index`` 函数会返回一个文件名列表,
你可以直接使用 ``for-in`` 循环处理文件. ====Example 1-47. 使用 os.listdir 搜索文件系统====[eg-1-47] ```
File: os-path-walk-example-2.py 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 *B*.\aifc-example-1.py
.\anydbm-example-1.py
.\array-example-1.py
...*b*
``` 如果你不想列出所有的文件 (基于性能或者是内存的考虑) , [Example 1-48 #eg-1-48] 展示了另一种方法.
这里 //DirectoryWalker// 类的行为与序列对象相似, 一次返回一个文件. (generator?) ====Example 1-48. 使用 DirectoryWalker 搜索文件系统====[eg-1-48] ```
File: os-path-walk-example-3.py 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 *B*.\aifc-example-1.py
.\anydbm-example-1.py
.\array-example-1.py
...*b*
``` 注意 //DirectoryWalker// 类并不检查传递给 ``_ _getitem_ _`` 方法的索引值.
这意味着如果你越界访问序列成员(索引数字过大)的话, 这个类将不能正常工作. 最后, 如果你需要处理文件大小和时间戳, [Example 1-49 #eg-1-49] 给出了一个类,
它返回文件名和它的 ``os.stat`` 属性(一个元组). 这个版本在每个文件上都能节省一次或两次
``stat`` 调用( ``os.path.isdir`` 和 ``os.path.islink`` 内部都使用了 ``stat`` ),
并且在一些平台上运行很快. ====Example 1-49. 使用 DirectoryStatWalker 搜索文件系统====[eg-1-49] ```
File: os-path-walk-example-4.py import os, stat class DirectoryStatWalker:
# a forward iterator that traverses a directory tree, and
# returns the filename and additional file information 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)
st = os.stat(fullname)
mode = st[stat.ST_MODE]
if stat.S_ISDIR(mode) and not stat.S_ISLNK(mode):
self.stack.append(fullname)
return fullname, st for file, st in DirectoryStatWalker("."):
print file, st[stat.ST_SIZE] *B*.\aifc-example-1.py 336
.\anydbm-example-1.py 244
.\array-example-1.py 526*b*
```

python标准库介绍——2 os.path模块详解的更多相关文章

  1. 转载的:Python os 和 os.path模块详解

    os.getcwd()获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录:相当于shell下cd os.curdi ...

  2. python标准库介绍——1 os详解

    == os 模块 == ``os`` 模块为许多操作系统函数提供了统一的接口. 这个模块中的大部分函数通过对应平台相关模块实现, 比如 ``posix`` 和 ``nt. os`` 模块会在第一次导入 ...

  3. Node入门教程(8)第六章:path 模块详解

    path 模块详解 path 模块提供了一些工具函数,用于处理文件与目录的路径.由于windows和其他系统之间路径不统一,path模块还专门做了相关处理,屏蔽了彼此之间的差异. 可移植操作系统接口( ...

  4. Python -- 标准库 文件管理 (部分os包,shutil包)

    在操作系统下,用户可以通过操作系统的命令来管理文件,参考linux文件管理相关命令.Python标准库则允许我们从Python内部管理文件.相同的目的,我们有了两条途径.尽管在Python调用标准库的 ...

  5. (转)python之os,sys模块详解

    python之sys模块详解 原文:http://www.cnblogs.com/cherishry/p/5725184.html sys模块功能多,我们这里介绍一些比较实用的功能,相信你会喜欢的,和 ...

  6. 小白的Python之路 day5 os,sys模块详解

    os模块详解 1.作用: 提供对操作系统调用的接口 2.常用方法: os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径os.chdir("dirname" ...

  7. Python中操作HTTP请求的urllib模块详解

    urllib 是 Python 标准库中用于网络请求的库.该库有四个模块,分别是urllib.request,urllib.error,urllib.parse,urllib.robotparser. ...

  8. python标准库介绍——10 sys 模块详解

    ==sys 模块== ``sys`` 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分. === 处理命令行参数=== 在解释器启动后, ``argv`` 列表包含了传递给脚本的所有 ...

  9. python标准库介绍——27 random 模块详解

    ==random 模块== "Anyone who considers arithmetical methods of producing random digits is, of cour ...

随机推荐

  1. window系统下调度数据库类型资源库中的kettle job

    已经存在kettle的一个资源库enfo,在目录/works/wxj下面有一个job (testmailsuccess.kjb)如何实现手工在kettle外部执行此job和让系统每天定时的调用此job ...

  2. sublime同步侧边栏与窗体的颜色

    Ctrl+Shift+P -> install -> 搜索安装包 SyncedSidebarBg,自动同步侧边栏底色为编辑窗口底色. P.S. 有时改完后侧边栏颜色没变化,不知什么原因,打 ...

  3. [Node.js]23. Level 4: Semantic versioning

    Update the versions on your dependencies to be a little more flexible, adding the ~ in front of your ...

  4. 【Nodejs】使用put方式向后端查询数据并在页面显示

    前端代码: <!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Ty ...

  5. 代码录播:jQueryMobile 实现一个简单的弹出框效果

    今天给大家带来的是 jQueryMobile 实现一个简单的弹出框效果,有兴趣的童鞋可以试试哦~ ^_^ 阅读原文:www.gbtags.com  

  6. UITableViewCell 取消分隔线

    方法一: [historyTodayTableVC setSeparatorStyle:UITableViewCellSeparatorStyleNone]; 方法二: [historyTodayTa ...

  7. 关于Haxe3新特性“内联构造方法”的解释

    学习过C/C++的童鞋们应该了解inline即内联机制的意义,Haxe语言也很好的支持内联机制,让开发者可以自己在空间效率和时间效率上进行取舍. 从Haxe3开始,构造方法也可以使用inline关键字 ...

  8. PHP高级教程-安全邮件

    PHP Secure E-mails 在上一节中的 PHP e-mail 脚本中,存在着一个漏洞. PHP E-mail 注入 首先,请看上一章中的 PHP 代码: <html> < ...

  9. [转]自定义Drawable实现灵动的红鲤鱼动画(上篇)

    此篇中的小鱼动画是模仿国外一个大牛做的flash动画,第一眼就爱上它了,简约灵动又不失美学,于是抽空试着尝试了一下,如下是我用Android实现的效果图:   小鱼儿 由于整个绘制分析过程比较繁琐所以 ...

  10. C语言的角落——C之很常使用特性(一)

    本文搜集整理了一些之前博客中没有提到的,C语言不经常使用的特性,算是对C系列的最后一次补充. 对C语言有兴趣的朋友能够浏览一下,查漏补缺. 变长參数列表 <stdarg.h> 头文件定义了 ...