python3 0219 File

目录

读和写文件

open()疑问:

几种模式:

file的方法:

pickle 模块


读和写文件

open()疑问:

  1. r+,指针在开始,还是结尾

  2. f.read(),为什么读不出信息
  3. newline=None、\r、\n、\r\n、‘’,区分写入和读出。待答疑,参考https://www.jianshu.com/p/0b0337df165a
On input, if newline is None, universal newlines mode is
  enabled.Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
On output, if newline is None, any '\n' characters written are
  translated to the system default line separator, os.linesep. If
  newline is '' or '\n', no translation takes place. If newline is any
  of the other legal values, any '\n' characters written are translated
  to the given string.
r+
#首次默认,指针在开始位置,进行读、写都是在开始位置写入(如果文件有内容,则写入N个字符,会覆盖文件已有N个字符)
#若先读,再写。则写入时,从读之后的指针位置开始写入
#若先写,再读。则写入后,指针后面还有字符,从写入后指针的位置开始读出

w+
#这种模式,再做读、写操作前,会先truncate已有文件内容,做覆盖操作。如果第一个操作时读,则读出来的内容是空

几种模式:

模式rr+ww+aa+xx+
++ + + +
 +++++++
创建  ++++++
覆盖  ++    
指针在开始++++  ++
指针在结尾    ++  

 

注意:mode含有b,不可指定encoding参数

python bytes和str两种类型可以通过函数encode()和decode()相互转换,
str→bytes:encode()方法。str通过encode()方法可以转换为bytes。
bytes→str:decode()方法。如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法。

file的方法:

  1. f.seek(),python3会出现无法从结束和当前位置移动指针,解决办法参考https://blog.csdn.net/qq_26442553/article/details/81705050
  2. f.read(size),默认或复数,返回全部
  3. f.write(str)
  4. f.readline()会从文件中读取单独的一行。换行符为 '\n'。f.readline() 如果返回一个空字符串, 说明已经已经读取到最后一行。
  5. f.readlines(sizehint),默认全部行,可以用给定的sizehint分割行
  6. f.tell()返回当前指针位置
  7. f.close()关闭并释放资源
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值