在Python open读写文件实现脚本的详细介绍

开发 后端
在Python open读写文件实现脚本的实际操作过程中,你对其的相关步骤中的读文件如果有兴趣了解的话,你就可以点击以下的文章。

在Python open读写文件实现脚本

在实际使用open打开相关文件之后一定要记得要调用文件对象的close()的相关方法。比如可以用try/finally语句来确保最后是否能关闭文件。以下就是文章的相关内容的详细接介绍,望你会有所收获。

  1. file_object = open('thefile.txt')  
  2. try:  
  3. all_the_text = file_object.read( )  
  4. finally:  
  5. file_object.close( ) 

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

读文件

读文本文件

  1. input = open('data', 'r') 

以上的相关代码就是Python open读写文件中实现脚本第二个参数默认为r

  1. input = open('data') 

读二进制文件

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

读取所有内容

  1. file_object = open('thefile.txt')  
  2. try:  
  3. all_the_text = file_object.read( )  
  4. finally:  
  5. file_object.close( ) 

 

读固定字节

  1. file_object = open('abinfile', 'rb')  
  2. try:  
  3. while True:  
  4. chunk = file_object.read(100)  
  5. if not chunk:  
  6. break  
  7. do_something_with(chunk)  
  8. finally:  
  9. file_object.close( ) 

 

 以上就是对Python open读写文件实现脚本相关的内容的部分介绍,望你会有所收获。

【编辑推荐】

  1. Python嵌入c中时应该链接的库有哪些
  2. Python脚本与C++程序互相调用的实际操作
  3. Python标准库的强大功能的相关介绍
  4. 用Python生成不依赖dll的exe的操作步骤简介
  5. 用Python生成不依赖dll的exe的操作步骤简介
责任编辑:佚名 来源: 博客园
相关推荐

2010-02-23 10:32:20

Python 脚本

2010-03-17 14:18:27

Python open

2019-11-19 11:20:25

Python数据结构Windows

2010-03-10 13:42:44

Python脚本

2010-07-21 13:17:52

Perl文件读写

2010-03-26 15:28:05

Python编写

2010-03-23 13:50:24

python教程

2010-03-17 17:06:10

python脚本语言

2010-03-26 17:17:37

Python特色

2010-06-12 15:17:08

MySQL 5.0

2011-06-15 15:16:54

Session

2010-03-05 10:50:17

2010-03-05 10:24:33

2010-03-05 11:18:52

Linux shell

2010-03-05 11:58:52

2010-03-05 13:09:23

Linux shell

2010-03-05 13:19:23

2010-03-05 12:50:38

Linux shell

2010-03-05 13:00:46

2010-03-25 12:33:14

Python脚本文件
点赞
收藏

51CTO技术栈公众号