Python3读取文件常用方法实例分析

yipeiwu_com5年前Python基础

本文实例讲述了Python3读取文件常用方法。分享给大家供大家参考。具体如下:

''''' 
Created on Dec 17, 2012 
读取文件 
@author: liury_lab 
''' 
# 最方便的方法是一次性读取文件中的所有内容放到一个大字符串中: 
all_the_text = open('d:/text.txt').read() 
print(all_the_text) 
all_the_data = open('d:/data.txt', 'rb').read() 
print(all_the_data) 
# 更规范的方法 
file_object = open('d:/text.txt') 
try: 
  all_the_text = file_object.read() 
  print(all_the_text) 
finally: 
  file_object.close() 
# 下面的方法每行后面有‘\n'  
file_object = open('d:/text.txt') 
try: 
  all_the_text = file_object.readlines() 
  print(all_the_text) 
finally: 
  file_object.close() 
# 三句都可将末尾的'\n'去掉  
file_object = open('d:/text.txt') 
try: 
  #all_the_text = file_object.read().splitlines() 
  #all_the_text = file_object.read().split('\n') 
  all_the_text = [L.rstrip('\n') for L in file_object] 
  print(all_the_text) 
finally: 
  file_object.close() 
# 逐行读 
file_object = open('d:/text.txt') 
try: 
  for line in file_object: 
    print(line, end = '') 
finally: 
  file_object.close() 
# 每次读取文件的一部分 
def read_file_by_chunks(file_name, chunk_size = 100):   
  file_object = open(file_name, 'rb') 
  while True: 
    chunk = file_object.read(chunk_size) 
    if not chunk: 
      break 
    yield chunk 
  file_object.close() 
for chunk in read_file_by_chunks('d:/data.txt', 4): 
  print(chunk)

输出如下:

hello python
hello world
b'ABCDEFG\r\nHELLO\r\nhello'
hello python
hello world
['hello python\n', 'hello world']
['hello python', 'hello world']
hello python
hello worldb'ABCD'
b'EFG\r'
b'\nHEL'
b'LO\r\n'
b'hell'
b'o'

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python脚本实现Web漏洞扫描工具

这是去年毕设做的一个Web漏洞扫描小工具,主要针对简单的SQL注入漏洞、SQL盲注和XSS漏洞,代码是看过github外国大神(听说是SMAP的编写者之一)的两个小工具源码,根据里面的思...

python实现五子棋人机对战游戏

python实现五子棋人机对战游戏

本文代码基于 python3.6 和 pygame1.9.4。 五子棋比起我之前写的几款游戏来说,难度提高了不少。如果是人与人对战,那么,电脑只需要判断是否赢了就可以。如果是人机对战,那...

pygame 精灵的行走及二段跳的实现方法(必看篇)

pygame 精灵的行走及二段跳的实现方法(必看篇)

不得不承认《Python游戏编程入门》这本书翻译、排版非常之烂,但是里面的demo还是很好的,之前做了些改编放到这里。 先是素材: 背景 精灵 所有素材均取自此书 接下来就是精灵类的...

python中time库的实例使用方法

time是python中处理时间的标准库 计算机时间的表达 提供获取系统时间并格式化输出功能 提供系统级精确计时功能,用于程序性能分析 用法:import time 函...

python实现淘宝购物系统

本文实例为大家分享了python淘宝购物系统的具体代码,供大家参考,具体内容如下 代码如下: #刚创建账户所拥有的钱 money = 0 #定义商品列表 goods_list =...