跟老齐学Python之不要红头文件(2)
文件的属性
所谓属性,就是能够通过一个文件对象得到的东西。
>>> f = open("131.txt","a")
>>> f.name
'131.txt'
>>> f.mode #显示当前文件打开的模式
'a'
>>> f.closed #文件是否关闭,如果关闭,返回True;如果打开,返回False
False
>>> f.close() #关闭文件的内置函数
>>> f.closed
True
文件的有关状态
很多时候,我们需要获取一个文件的有关状态(有时候成为属性,但是这里的文件属性和上面的文件属性是不一样的,可是,我觉得称之为文件状态更好一点),比如创建日期,访问日期,修改日期,大小,等等。在os模块中,有这样一个方法,能够解决此问题:
>>> import os
>>> file_stat = os.stat("131.txt") #查看这个文件的状态
>>> file_stat #文件状态是这样的。从下面的内容,有不少从英文单词中可以猜测出来。
posix.stat_result(st_mode=33204, st_ino=5772566L, st_dev=2049L, st_nlink=1, st_uid=1000, st_gid=1000, st_size=69L, st_atime=1407897031, st_mtime=1407734600, st_ctime=1407734600)
>>> file_stat.st_ctime #这个是文件创建时间
1407734600.0882277 #换一种方式查看这个时间
>>> import time
>>> time.localtime(file_stat.st_ctime) #这回看清楚了。
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=11, tm_hour=13, tm_min=23, tm_sec=20, tm_wday=0, tm_yday=223, tm_isdst=0)
以上关于文件状态和文件属性的内容,在对文件的某些方面进行判断和操作的时候或许会用到。特别是文件属性。比如在操作文件的时候,我们经常要首先判断这个文件是否已经关闭或者打开,就需要用到file.closed这个属性来判断了。
文件的内置函数
>>> dir(file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
>>>
这么多内置函数,不会都讲述,只能捡着重点的来实验了。
>>> f = open("131.txt","r")
>>> f.read()
'My name is qiwsir.\nMy website is qiwsir.github.io\nAha,I like program\n'
>>>
file.read()能够将文件中的内容全部读取过来。特别注意,这是返回一个字符串,而且是将文件中的内容全部读到内存中。试想,如果内容太多是不是就有点惨了呢?的确是,千万不要去读大个的文件。
>>> contant = f.read()
>>> type(contant)
<type 'str'>
如果文件比较大了,就不要一次都读过来,可以转而一行一行地,用readline






