python标准库学习2

来源:转载

列出指定目录中的所有文件:

import osfor file in os.listdir( "../src" ): print file

获得,修改当前的目录

import os# where are we?cwd = os.getcwd()print "1", cwd# go downos.chdir( "../" )print "2", os.getcwd()# go back upos.chdir( os.pardir )print "3", os.getcwd()

创建目录,删除目录

import osfp = open( "../src/levels/file", "w" )fp.write( "inspector praline" )fp.close()os.remove( "../src/levels/file" )os.removedirs( "../src/levels" )

返回文件的信息:

import osimport timefile = "../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 filenamest = os.stat( file )print "stat", filedump( st )print## get stats for an open filefp = open( file )st = os.fstat( fp.fileno() )print "fstat", filedump( 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 osfilename = "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`` 只分割出最后一项(不带斜杠). 欢迎转载,共同进步 如果你喜欢我喜欢的,你关心我关心的,大家交个朋友,一起分享,交流,进步。 我的邮箱:rollenholt#qq.com

分享给朋友:
您可能感兴趣的文章:
随机阅读: