国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python3讀取文件常用方法實例分析

2020-01-04 18:10:05
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了Python3讀取文件常用方法,以實例形式較為詳細的分析了Python一次性讀取、逐行讀取及讀取文件一部分的實現技巧,需要的朋友可以參考下

本文實例講述了Python3讀取文件常用方法。分享給大家供大家參考。具體如下:

 

 
  1. '''''''  
  2. Created on Dec 17, 2012  
  3. 讀取文件  
  4. @author: liury_lab  
  5. ''' 
  6. # 最方便的方法是一次性讀取文件中的所有內容放到一個大字符串中:  
  7. all_the_text = open('d:/text.txt').read()  
  8. print(all_the_text)  
  9. all_the_data = open('d:/data.txt''rb').read()  
  10. print(all_the_data)  
  11. # 更規范的方法  
  12. file_object = open('d:/text.txt')  
  13. try:  
  14. all_the_text = file_object.read()  
  15. print(all_the_text)  
  16. finally:  
  17. file_object.close()  
  18. # 下面的方法每行后面有‘/n'  
  19. file_object = open('d:/text.txt')  
  20. try:  
  21. all_the_text = file_object.readlines()  
  22. print(all_the_text)  
  23. finally:  
  24. file_object.close()  
  25. # 三句都可將末尾的'/n'去掉  
  26. file_object = open('d:/text.txt')  
  27. try:  
  28. #all_the_text = file_object.read().splitlines()  
  29. #all_the_text = file_object.read().split('/n')  
  30. all_the_text = [L.rstrip('/n'for L in file_object]  
  31. print(all_the_text)  
  32. finally:  
  33. file_object.close()  
  34. # 逐行讀  
  35. file_object = open('d:/text.txt')  
  36. try:  
  37. for line in file_object:  
  38. print(line, end = '')  
  39. finally:  
  40. file_object.close()  
  41. # 每次讀取文件的一部分  
  42. def read_file_by_chunks(file_name, chunk_size = 100):  
  43. file_object = open(file_name, 'rb')  
  44. while True:  
  45. chunk = file_object.read(chunk_size)  
  46. if not chunk:  
  47. break 
  48. yield chunk  
  49. file_object.close()  
  50. for chunk in read_file_by_chunks('d:/data.txt'4):  
  51. print(chunk) 

輸出如下:

 

 
  1. hello python 
  2. hello world 
  3. b'ABCDEFG/r/nHELLO/r/nhello' 
  4. hello python 
  5. hello world 
  6. ['hello python/n''hello world'
  7. ['hello python''hello world'
  8. hello python 
  9. hello worldb'ABCD' 
  10. b'EFG/r' 
  11. b'/nHEL' 
  12. b'LO/r/n' 
  13. b'hell' 
  14. b'o' 

希望本文所述對大家的Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南汇区| 砚山县| 阿鲁科尔沁旗| 巴彦县| 扎兰屯市| 金塔县| 剑河县| 阿拉善盟| 平和县| 金沙县| 大同市| 铁岭市| 巨野县| 利津县| 阿克| 天祝| 依兰县| 泰和县| 新竹县| 枞阳县| 丹寨县| 利辛县| 青海省| 右玉县| 许昌市| 阿坝县| 延边| 柯坪县| 洪洞县| 如皋市| 泰州市| 霍林郭勒市| 秭归县| 嘉禾县| 房产| 江永县| 定陶县| 绥宁县| 茂名市| 饶阳县| 台中县|