python标准库学习2
2011-08-08 13:18 Rollen Holt 阅读(843) 评论(2) 编辑 收藏 举报列出指定目录中的所有文件:
import os for file in os.listdir( "../src" ): print file
获得,修改当前的目录
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()
创建目录,删除目录
import os fp = open( "../src/levels/file", "w" ) fp.write( "inspector praline" ) fp.close() os.remove( "../src/levels/file" ) os.removedirs( "../src/levels" )
返回文件的信息:
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 accessed:", 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
处理文件名
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/little\pony
注意这里的 ``split`` 只分割出最后一项(不带斜杠).
==============================================================================
本博客已经废弃,不在维护。新博客地址:http://wenchao.ren
我喜欢程序员,他们单纯、固执、容易体会到成就感;面对压力,能够挑灯夜战不眠不休;面对困难,能够迎难而上挑战自我。他
们也会感到困惑与傍徨,但每个程序员的心中都有一个比尔盖茨或是乔布斯的梦想“用智慧开创属于自己的事业”。我想说的是,其
实我是一个程序员
==============================================================================