FlySky 2010-03-12
Python模块作为计算机应用语言经常被用到的语言,用处也颇为广泛,下面的文章就是介绍Python模块如何在文件中获取相关的信息,如果你对其感兴趣,你可以浏览我们的文章,希望你会有所收获。
使用Python模块,可以从现有文件中获取信息。使用“os”模块和“stat”模块可以获取文件的基本信息:
view plaincopy to clipboardprint? import os import stat import time<DIV></DIV> fileStats = os.stat ( 'test.txt' ) fileInfo = { 'Size' : fileStats [ stat.ST_SIZE ], 'LastModified' : time.ctime ( fileStats [ stat.ST_MTIME ] ), 'LastAccessed' : time.ctime ( fileStats [ stat.ST_ATIME ] ), 'CreationTime' : time.ctime ( fileStats [ stat.ST_CTIME ] ), 'Mode' : fileStats [ stat.ST_MODE ] } for infoField, infoValue in fileInfo: print infoField, ':' + infoValue if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ): print 'Directory. ' else: print 'Non-directory.' import os import stat import time fileStats = os.stat ( 'test.txt' ) fileInfo = { 'Size' : fileStats [ stat.ST_SIZE ], 'LastModified' : time.ctime ( fileStats [ stat.ST_MTIME ] ), 'LastAccessed' : time.ctime ( fileStats [ stat.ST_ATIME ] ), 'CreationTime' : time.ctime ( fileStats [ stat.ST_CTIME ] ), 'Mode' : fileStats [ stat.ST_MODE ] } for infoField, infoValue in fileInfo: print infoField, ':' + infoValue if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ): print 'Directory. ' else: print 'Non-directory.'
上面这个例子创建了一个包含文件基本信息的dictionary。然后显示了相关信息,并且告诉我们打开的是否为目录。我们也可以试一下打开的是否是其它几种类型:
view plaincopy to clipboardprint? import os import stat fileStats = os.stat ( 'test.txt' ) fileMode = fileStats [ stat.ST_MODE ] if stat.S_ISREG ( fileStats [ stat.ST_MODE ] ): print 'Regular file.' elif stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ): print 'Directory.' elif stat.S_ISLNK ( fileStats [ stat.ST_MODE ] ): print 'Shortcut.' elif stat.S_ISSOCK ( fileStats [ stat.ST_MODE ] ): print 'Socket.' elif stat.S_ISFIFO ( fileStats [ stat.ST_MODE ] ): print 'Named pipe.' elif stat.S_ISBLK ( fileStats [ stat.ST_MODE ] ): print 'Block special device.' elif stat.S_ISCHR ( fileStats [ stat.ST_MODE ] ): print 'Character special device.' import os import stat fileStats = os.stat ( 'test.txt' ) fileMode = fileStats [ stat.ST_MODE ] if stat.S_ISREG ( fileStats [ stat.ST_MODE ] ): print 'Regular file.' elif stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ): print 'Directory.' elif stat.S_ISLNK ( fileStats [ stat.ST_MODE ] ): print 'Shortcut.' elif stat.S_ISSOCK ( fileStats [ stat.ST_MODE ] ): print 'Socket.' elif stat.S_ISFIFO ( fileStats [ stat.ST_MODE ] ): print 'Named pipe.' elif stat.S_ISBLK ( fileStats [ stat.ST_MODE ] ): print 'Block special device.' elif stat.S_ISCHR ( fileStats [ stat.ST_MODE ] ): print 'Character special device.'
另外,我们不用Python模块,用“os.path”来获取基本信息: