欢迎来到资源库(www.zyku.net)

Python教程

当前位置:首页 > 网络编程 > Python教程 > open

Python open读写文件实现脚本

时间:2021-04-24|栏目:Python教程|点击:|我要投稿

1.open

使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。

file_object = open('thefile.txt')
try:
  all_the_text = file_object.read( )
finally:
  file_object.close( )

注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。

2.读文件

读文本文件

input = open('data', 'r')
#第二个参数默认为r
input = open('data')

读二进制文件

input = open('data', 'rb')

读取所有内容

file_object = open('thefile.txt')
try:
  all_the_text = file_object.read( )
finally:
  file_object.close( )

读固定字节

file_object = open('abinfile', 'rb')
try:
  while True:
    chunk = file_object.read(100)
    if not chunk:
      break
    do_something_with(chunk)
finally:
  file_object.close( )

读每行

list_of_all_the_lines = file_object.readlines( )

如果文件是文本文件,还可以直接遍历文件对象获取每行:

for line in file_object:
process line

3.写文件

写文本文件

output = open('data', 'w')

写二进制文件

output = open('data', 'wb')

追加写文件

output = open('data', 'w+')

写数据

file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )

写入多行

file_object.writelines(list_of_text_strings)

注意,调用writelines写入多行在性能上会比使用write一次性写入要高。

(资源库 www.zyku.net)

上一篇:Python 过滤字符串的技巧,map与itertools.imap

栏    目:Python教程

下一篇:Python linecache.getline()读取文件中特定一行的脚本

本文标题:Python open读写文件实现脚本

本文地址:https://www.zyku.net/python/2190.html

关于我们 | 版权申明 | 寻求合作 |

重要申明:本站所有的文章、图片、评论等内容,均由网友发表或上传并维护或收集自网络,仅供个人学习交流使用,版权归原作者所有。

如有侵犯您的版权,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:95148658 | 邮箱:mb8#qq.com(#换成@)

苏ICP备2020066115号-1

本网站由提供CDN加速/云存储服务