例子,pythonbiaozhunku/ target=_blank class=infotextkey>python标准库的用法。
1,列出指定目录中的所有文件:
复制代码 代码示例:
import os
for file in os.listdir( "../src" ):
print file
2,获得,修改当前的目录
复制代码 代码示例:
import os
# where are we?
cwd = os.getcwd()
print "1", cwd
# go down
os.chdir( "../" )
print "2", os.getcwd()
# go back up
os.chdir( os.pardir )
print "3", os.getcwd()
3,创建目录,删除目录
复制代码 代码示例:
import os
fp = open( "../src/levels/file", "w" )
fp.write( "inspector praline" )
fp.close()
os.remove( "../src/levels/file" )
os.removedirs( "../src/levels" )
4,返回文件的信息:
复制代码 代码示例:
import os
import time
file = "../src/hello.xml"
def dump( st ):
mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime = st
print "- size:", size, "bytes"
print "- owner:", uid, gid
print "- created:", time.ctime( ctime )
print "- last acces
sed:", time.ctime( atime )
print "- last modified:", time.ctime( mtime )
print "- mode:", oct( mode )
print "- inode/dev:", ino, dev
#
# get stats for a filename
st = os.stat( file )
print "stat", file
dump( st )
print
#
# get stats for an open file
fp = open( file )
st = os.fstat( fp.fileno() )
print "fstat", file
dump( st )
输出结果为:
stat ../src/hello.xml
- size: 274 bytes
- owner: 0 0
- created: Sun Aug 07 20:45:31 2011
- last accessed: Mon Aug 08 12:34:28 2011
- last modified: Mon Aug 08 12:34:28 2011
- mode: 0100666
- inode/dev: 0 0
fstat ../src/hello.xml
- size: 274 bytes
- owner: 0 0
- created: Sun Aug 07 20:45:31 2011
- last accessed: Mon Aug 08 12:34:28 2011
- last modified: Mon Aug 08 12:34:28 2011
- mode: 0100666
- inode/dev: 6192449487670266 0
5,处理文件名
复制代码 代码示例:
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 ) )
输出为;using nt ...
split => ('my/little', 'pony')
splitext => ('my/little/pony', '')
dirname => my/little
basename => pony
join => my/littlepony
注意,此处的 ``split`` 只分割出最后一项(不带斜杠)。