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 ...
随机推荐
- hadoop fs:du & count统计hdfs文件(目录下文件)大小的用法
hadoop fs 更多用法,请参考官网:http://hadoop.apache.org/docs/r1.0.4/cn/hdfs_shell.html 以下是我的使用hadoop fs -du统计文 ...
- Reduce Task的学习笔记
MapReduce五大过程已经分析过半了.上次分析完Map的过程,着实花费了我的非常多时间.只是收获非常大,值得了额,这次用相同的方法分析完了Reduce的过程,也算是彻底摸透了MapReduce思想 ...
- [Algorithm] Tree: Lowest Common Ancestor
By given a tree structure, task is to find lowest common ancestor: For example, LCA(4, 5) --> > ...
- Faiss学习:一
在多个GPU上运行Faiss以及性能测试 一.Faiss的基本使用 1.1在CPU上运行 Faiss的所有算法都是围绕index展开的.不管运行搜索还是聚类,首先都要建立一个index. import ...
- 使用Editplus配置PHP调试环境
工欲善其事必先利其器.近期看了非常多PHP的IDE介绍.最后选择了Editplus.以下说说一些PHP的调试环境配置问题. 1. 加入PHP模板 第一步 新建->其他->php 第二步 输 ...
- Strange Addition
http://codeforces.com/problemset/problem/305/A 这题就是意思没看懂,一开始以为只要个位数只要一个为0就能相加,没想到到CF里面提交第三组就过不了,才发现是 ...
- 把mysql数据库生成数据字典,直接可用
便于查看数据库表.字段,做一个数据字典是很有必要的,下面只需要简单更改下配置就可以用了,样式也是挺好的. <?php header('content-type:text/html;charset ...
- 翻转子串(string+KMP+程序猿面试金典)
翻转子串 參与人数:1197时间限制:3秒空间限制:32768K 通过比例:35.03% 最佳记录:0 ms|8552K(来自 ) 题目描写叙述 假定我们都知道很高效的算法来检查一个单词是否为其它字符 ...
- 《Java并发编程实战》第九章 图形用户界面应用程序界面 读书笔记
一.为什么GUI是单线程化 传统的GUI应用程序通常都是单线程的. 1. 在代码的各个位置都须要调用poll方法来获得输入事件(这样的方式将给代码带来极大的混乱) 2. 通过一个"主事件循环 ...
- python——实例方法、静态方法、类方法、类变量和实例变量浅析
概述: 实例方法就是类的实例能够使用的方法. 静态方法是一种普通函数,就位于类定义的命名空间中,它不会对任何实例类型进行操作.使用装饰器@staticmethod定义静态方法.类对象和实例都可调用静态 ...