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,读取,文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
YUI学习笔记(4)
2009-03-10 18:25:00
python使用matplotlib的savefig保存时图片保存不完整的问题
2021-07-04 11:50:22
![](https://img.aspxhome.com/file/2023/3/134653_0s.png)
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
![](https://img.aspxhome.com/file/2023/7/63957_0s.jpg)
利用20行Python 代码实现加密通信
2023-04-22 06:18:54
Python之二维正态分布采样置信椭圆绘制
2021-04-08 06:39:09
![](https://img.aspxhome.com/file/2023/4/83824_0s.jpg)
Python图像锐化与边缘检测之Sobel与Laplacian算子详解
2023-01-25 01:36:04
![](https://img.aspxhome.com/file/2023/1/95691_0s.png)
Vue Socket.io源码解读
2024-06-05 15:28:35
![](https://img.aspxhome.com/file/2023/4/123144_0s.png)
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
![](https://img.aspxhome.com/file/2023/7/113527_0s.png)
asp使用XMLHTTP下载远程数据输出到浏览器
2007-11-04 10:34:00
MAC系统IDEA颜值插件MaterialThemeUI
2022-12-26 00:29:07
![](https://img.aspxhome.com/file/2023/8/132428_0s.jpg)
Python实现以主程序的形式执行模块
2022-01-14 01:37:00
![](https://img.aspxhome.com/file/2023/8/86578_0s.png)
mysql中写判断语句的方法总结
2024-01-21 15:17:30
![](https://img.aspxhome.com/file/2023/4/70394_0s.png)