Python模块的几种类型简介
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”来获取基本信息:
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16