• 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读写文件,追加文本内容实例

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

通过本文主要向大家介绍了python open rb,python open,python open函数,python with open,python with open as等相关知识,希望对您有所帮助,也希望大家支持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
</div>

3.写文件写文本文件output = open('data.txt', 'w')

写二进制文件output = open('data.txt', 'wb')

追加写文件output = open('data.txt', 'a')

output .write("\n都有是好人")

output .close( )
</div>

写数据file_object = open('thefile.txt', 'w')

file_object.write(all_the_text)
file_object.close( )
</div>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

</div>

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

  • Python文件操作,open读写文件,追加文本内容实例
  • Python open读写文件实现脚本

相关文章

  • Python使用面向对象方式创建线程实现12306售票系统
  • 在CentOS上配置Nginx+Gunicorn+Python+Flask环境的教程
  • python网络编程之文件下载实例分析
  • Python变量和数据类型详解
  • python3图片转换二进制存入mysql
  • 用于统计项目中代码总行数的Python脚本分享
  • 详解Python实现按任意键继续/退出的功能
  • Python smallseg分词用法实例分析
  • Python Paramiko模块的安装与使用详解
  • Python中的map()函数和reduce()函数的用法

文章分类

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

最近更新的内容

    • pygame学习笔记(3):运动速率、时间、事件、文字
    • 使用Python脚本将绝对url替换为相对url的教程
    • Python实现拷贝多个文件到同一目录的方法
    • Python selenium 三种等待方式详解(必会)
    • python中enumerate函数遍历元素用法分析
    • Python functools模块学习总结
    • Python 抓取动态网页内容方案详解
    • python统计文本字符串里单词出现频率的方法
    • python中常用检测字符串相关函数汇总
    • Python遍历文件夹和读写文件的实现代码

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

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