python-文件操作

正常的文件操作都分三步走:
打开文件
操作文件
关闭文件

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

几个常用方法
read() #读取文件所有内容并返回字符串
readline() #读取一行
next() #读取下一行
readlines() #读取所有内容,并返回列表(一行为列表的一个元素值)
write() #写一行
writelines(list) #写多行,参数为列表
seek() #句柄指针操作
tell() #当前句柄指针位置
truncate() #截取文件句柄头到当前位置的字符串,返回None
xreadlines() # 一行一行读,3.x版本已放弃此写法

事例代码:

>>> #代码示例
... #打开一个文件并写入
... fh = open('tfile','wb+')
>>> #文件句柄所在位置
... fh.tell()
0
>>> #写入一行
... fh.write('Life is like a roller coaster,live it,be happy,enjoy life.\n')
>>> #写入多行,参数为列表list
... fh.writelines(["The best way to make your dreams come true is to wake up.\n","If you're not making mistakes,you're not trying hard enough."])
>>> #返回文件句柄头
... fh.seek(0)
>>> #读一行
... fh.readline()
'Life is like a roller coaster,live it,be happy,enjoy life.\n'
>>> #读所有行,返回列表list
... fh.readlines()
['The best way to make your dreams come true is to wake up.\n', "If you're not making mistakes,you're not trying hard enough."]
>>> #返回文件句柄头
... fh.seek(0)
>>> #读取全部内容,返回字符串
... fh.read()
"Life is like a roller coaster,live it,be happy,enjoy life.\nThe best way to make your dreams come true is to wake up.\nIf you're not making mistakes,you're not trying hard enough."
>>> #返回文件句柄头
... fh.seek(0)
>>> fh.readline()
'Life is like a roller coaster,live it,be happy,enjoy life.\n'
>>> #读取当前位置
... fh.tell()
59
>>> #截取文件句柄头到当前位置的字符串
... fh.truncate()
>>> fh.seek(0)
>>> fh.read()
'Life is like a roller coaster,live it,be happy,enjoy life.\n'
>>> #读一行
... fh.seek(0)
>>> fh.next()
'Life is like a roller coaster,live it,be happy,enjoy life.\n'
>>> #关闭文件句柄
...

 

with语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:
。。。

 

转载于:https://www.cnblogs.com/fsllovexzd/p/10604699.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值