python标准库介绍——2 os.path模块详解
== 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模块详解的更多相关文章
- 转载的:Python os 和 os.path模块详解
os.getcwd()获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录:相当于shell下cd os.curdi ...
- python标准库介绍——1 os详解
== os 模块 == ``os`` 模块为许多操作系统函数提供了统一的接口. 这个模块中的大部分函数通过对应平台相关模块实现, 比如 ``posix`` 和 ``nt. os`` 模块会在第一次导入 ...
- Node入门教程(8)第六章:path 模块详解
path 模块详解 path 模块提供了一些工具函数,用于处理文件与目录的路径.由于windows和其他系统之间路径不统一,path模块还专门做了相关处理,屏蔽了彼此之间的差异. 可移植操作系统接口( ...
- Python -- 标准库 文件管理 (部分os包,shutil包)
在操作系统下,用户可以通过操作系统的命令来管理文件,参考linux文件管理相关命令.Python标准库则允许我们从Python内部管理文件.相同的目的,我们有了两条途径.尽管在Python调用标准库的 ...
- (转)python之os,sys模块详解
python之sys模块详解 原文:http://www.cnblogs.com/cherishry/p/5725184.html sys模块功能多,我们这里介绍一些比较实用的功能,相信你会喜欢的,和 ...
- 小白的Python之路 day5 os,sys模块详解
os模块详解 1.作用: 提供对操作系统调用的接口 2.常用方法: os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径os.chdir("dirname" ...
- Python中操作HTTP请求的urllib模块详解
urllib 是 Python 标准库中用于网络请求的库.该库有四个模块,分别是urllib.request,urllib.error,urllib.parse,urllib.robotparser. ...
- python标准库介绍——10 sys 模块详解
==sys 模块== ``sys`` 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分. === 处理命令行参数=== 在解释器启动后, ``argv`` 列表包含了传递给脚本的所有 ...
- python标准库介绍——27 random 模块详解
==random 模块== "Anyone who considers arithmetical methods of producing random digits is, of cour ...
随机推荐
- Windows 8.1 64位版本安装.Net Framework3.5
最近刚把个人电脑切换成了Win 8.1 64位版本,但在使用某些Ms的某此产品时会提示没有安装.Net Framework3.5,但按照他的提示需要在线安装而且速度很慢,因为之前搞过WinServer ...
- Android网络缓存的实现思路
在开发群里有多位同学问到了关于Android中网络缓存的问题.事实上不管是Android还是iOS,缓存的大致思路都是同样的,以下就几种情况下的缓存做一个大致的介绍.顺便说一下有些开源的网络请求框架已 ...
- Node.js程序在node-windows中不能运行
Node.js程序部分功能在命令行中运行良好,但在node-windows中不能运行,怎么回事? 答:路径问题. 请看如下的描述: My script runs fine on it's own, ...
- tcpdump-根据IP查看程序与服务都用了哪些端口
tcpdump -i em1 -tttt src 116.3.248.157 and port ! 6869 -nn -i 指定端口 -tttt 附带时间戳 -nn 解析域名与端口信息 ####### ...
- 火狐浏览器Firefox Firebug使用方法
什么是Firebug 从事了数年的Web开发工作,越来越觉得现在对WEB开发有了更高的要求.要写出漂亮的HTML代码:要编写精致的CSS样式表展示每个页面模块:要调试javascript给页面增加一些 ...
- 使用Editplus配置PHP调试环境
工欲善其事必先利其器.近期看了非常多PHP的IDE介绍.最后选择了Editplus.以下说说一些PHP的调试环境配置问题. 1. 加入PHP模板 第一步 新建->其他->php 第二步 输 ...
- 87. 再谈变体型Variant
在85. BASIC和LotusScript中的Variant一文中.我提到了BASIC风格的语言中的变体型Variant.由于下述种种原因.在LotusScript中常常要用到变体型. 1. ...
- Android的startActivityForResult不起作用
之前startActivityForResult一直用的好好的,今天发现怎么也不起作用.检查后发现有两点影响了. 1.android:launchMode="singleTask" ...
- webapp 里主要的 mate 用途
一.meta 标签分两大部分:HTTP 标题信息(http-equiv)和页面描述信息(name). 1.http-equiv 属性的 Content-Type 值(显示字符集的设定) 说明:设定页面 ...
- 2019年所有人必须要掌握的一个技能 - “AI思维”
或许很多人认为AI只是那些直接从事AI相关岗位的人必须要掌握的技能,但实际上,不分岗位所有人都需要一种能力,那就是“AI思维”.如果没能在合适的时机把自己的认知提升到一定程度,被替代是很自然的事情.在 ...