打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python文件操作,open读写文件,追加文本内容
  1. 1.open使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。  
  2. file_object = open('thefile.txt')  
  3. try:  
  4.  all_the_text = file_object.read( )  
  5. finally:  
  6.  file_object.close( )  
  7. 注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。  
  8. 2.读文件读文本文件input = open('data''r')  
  9. #第二个参数默认为r   
  10. input = open('data')  
  11.   
  12. 读二进制文件input = open('data''rb')  
  13. 读取所有内容file_object = open('thefile.txt')  
  14. try:  
  15.  all_the_text = file_object.read( )  
  16. finally:  
  17.  file_object.close( )  
  18. 读固定字节file_object = open('abinfile''rb')  
  19. try:  
  20.  while True:  
  21.  chunk = file_object.read(100)  
  22.  if not chunk:  
  23.  break  
  24.  do_something_with(chunk)  
  25. finally:  
  26.  file_object.close( )  
  27. 读每行list_of_all_the_lines = file_object.readlines( )  
  28. 如果文件是文本文件,还可以直接遍历文件对象获取每行:  
  29. for line in file_object:  
  30.  process line  
  31. 3.写文件写文本文件output = open('data.txt''w')  
  32. 写二进制文件output = open('data.txt''wb')  
  33. 追加写文件output = open('data.txt''a')  
  34.   
  35. output .write("\n都有是好人")  
  36.   
  37. output .close( )  
  38.   
  39. 写数据file_object = open('thefile.txt''w')  
  40. file_object.write(all_the_text)  
  41. file_object.close( )  


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python中的open函数
【Python 第32课】 写文件
python_处理文本文件
将python变量值写为文件保存
python 读取txt中文文本
python 中open()文件操作的方式
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服