• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python open读写文件实现脚本

Python open读写文件实现脚本

作者:mdxy-dxy 字体:[增加 减小] 来源:互联网

mdxy-dxy 通过本文主要向大家介绍了python open,python open rb,python open函数,python open 编码,python open a等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

1.open

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

file_object = open('thefile.txt')
try:
  all_the_text = file_object.read( )
finally:
  file_object.close( )
</div>

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

2.读文件

读文本文件

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

读二进制文件

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

读取所有内容

file_object = open('thefile.txt')
try:
  all_the_text = file_object.read( )
finally:
  file_object.close( )
</div>

读固定字节

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( )

</div>

读每行

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( )
</div>

写入多行
file_object.writelines(list_of_text_strings)

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

</div>

您可能想查找下面的文章:

  • python使用opencv进行人脸识别
  • Python文件操作,open读写文件,追加文本内容实例
  • Python+Opencv识别两张相似图片
  • Python+Opencv识别两张相似图片
  • Python中使用OpenCV库来进行简单的气象学遥感影像计算
  • Python中使用OpenCV库来进行简单的气象学遥感影像计算
  • Python编程中用close()方法关闭文件的教程
  • python通过openpyxl生成Excel文件的方法
  • 在Python下利用OpenCV来旋转图像的教程
  • 利用Python和OpenCV库将URL转换为OpenCV格式的方法

相关文章

  • Python中动态获取对象的属性和方法的教程
  • python在windows下实现ping操作并接收返回信息的方法
  • 深入源码解析Python中的对象与类型
  • python 测试实现方法
  • Python和GO语言实现的消息摘要算法示例
  • 使用py2exe在Windows下将Python程序转为exe文件
  • python去除空格和换行符的实现方法(推荐)
  • 解读Python中degrees()方法的使用
  • java直接调用python脚本的例子
  • python正则匹配抓取豆瓣电影链接和评论代码分享

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • 利用QT写一个极简单的图形化Python闹钟程序
    • 简单介绍Python的轻便web框架Bottle
    • 用Python编写脚本使IE实现代理上网的教程
    • Python中的localtime()方法使用详解
    • Python 网络编程起步(Socket发送消息)
    • python字典的常用操作方法小结
    • 详解Python2.x中对Unicode编码的使用
    • Python中用max()方法求最大值的介绍
    • Python学习笔记_数据排序方法
    • 浅谈function(函数)中的动态参数

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有