在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读写文件实现脚本相关的内容的部分介绍,望你会有所收获。

相关内容

    暂无相关文章

评论关闭