python 文件2学习

文件的状态


很多时候,我们需要获取一个文件的有关状态(也成为属性),比如创建日期,访问日期,修改日期,大小,等待。在os模块中,有这样一个方法,专门让我们查看文件的这些状态参数的。


>>> import os
>>> file_stat = os.stat("131.txt") #查看这个文件的状态
>>> file_stat 
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=72L, st_atime=1464751944L, st_mtime=1464757060L, st_ctime=1464751944L)
>>> file_stat.st_ctime  #文件的创建时间
1464751944.8917134
>>> import time
>>> time.localtime(file_stat.st_ctime) #这下时间就非常清楚了
time.struct_time(tm_year=2016, tm_mon=6, tm_mday=1, tm_hour=11, tm_min=32, tm_sec=24, tm_wday=2, tm_yday=153, tm_isdst=0)






read/readline/readlines


1)read:
如果指定了参数size,就按照该指定长度从文件中读取内容,否则,就读取全文。被读出来的内容,全部塞到一个字符串里面。这样有好处,就是东西都到内存里面了,随时取用,比较快捷:
2)readline:
那个可选参数size的含义同上。它则是以行为单位返回字符串,也就是每次读一行,一次循环,如果不限定size,直到最后一个返回的是空字符串,意味着文件末尾了(EOF)。
3)readlines:
size同上。它返回的是以行为单位的列表,即相当于先执行reasline(),得到每一行,然后把这一行的字符串作为列表中的元素塞到一个列表中,最后将此列表返回。


>>> f = open("you.md")
>>> content = f.read()
>>> content
'You Raise Me Up When I am down and, oh my soul, so weary; When troubles come and my heart burdened be; Then, I am still and wait here in the silence, Until you come and sit awhile with me. You raise me up, so I can stand on mountains; You raise me up, to walk on stormy seas; I am strong, when I am on your shoulders; You raise me up: To more than I can be.'
>>> f.close()


提示:养成一个好习惯,只要打开文件,不用该文件了,就一定要随手关闭它。如果不关闭它,它还驻留在内存中,后面又没有它的操作,浪费空间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值