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

作者:皮蛋 时间:2023-07-07 16:13:43 

本文实例讲述了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,读取,文件
0
投稿

猜你喜欢

  • YUI学习笔记(4)

    2009-03-10 18:25:00
  • python使用matplotlib的savefig保存时图片保存不完整的问题

    2021-07-04 11:50:22
  • python3 kubernetes api的使用示例

    2021-11-11 00:56:18
  • php session_start()出错原因分析及解决方法

    2024-06-07 15:44:29
  • python绘制字符画视频的示例代码

    2023-11-09 16:21:46
  • 利用20行Python 代码实现加密通信

    2023-04-22 06:18:54
  • Python之二维正态分布采样置信椭圆绘制

    2021-04-08 06:39:09
  • Python图像锐化与边缘检测之Sobel与Laplacian算子详解

    2023-01-25 01:36:04
  • Vue Socket.io源码解读

    2024-06-05 15:28:35
  • Python基于Tkinter实现的记事本实例

    2021-12-30 09:25:17
  • Python获取DLL和EXE文件版本号的方法

    2023-09-07 11:43:23
  • Oracle批量查询、删除、更新使用BULK COLLECT提高效率

    2023-07-14 03:15:52
  • javascript在事件监听方面的兼容性小结

    2024-04-29 13:45:19
  • Javascript中Eval函数的使用

    2024-03-24 19:55:23
  • python实现远程控制电脑

    2022-12-07 21:00:16
  • SQL Server中row_number函数用法入门介绍

    2024-01-26 22:45:04
  • asp使用XMLHTTP下载远程数据输出到浏览器

    2007-11-04 10:34:00
  • MAC系统IDEA颜值插件MaterialThemeUI

    2022-12-26 00:29:07
  • Python实现以主程序的形式执行模块

    2022-01-14 01:37:00
  • mysql中写判断语句的方法总结

    2024-01-21 15:17:30
  • asp之家 网络编程 m.aspxhome.com