python 读取文本文件

Python File object provides various ways to read a text file. The popular way is to use the readlines() method that returns a list of all the lines in the file. However, it’s not suitable to read a large text file because the whole file content will be loaded into the memory.

Python File对象提供了多种读取文本文件的方法。 流行的方法是使用readlines()方法,该方法返回文件中所有行的列表。 但是,不适合读取大文本文件,因为整个文件内容都将加载到内存中。

用Python读取大文本文件 (Reading Large Text Files in Python)

We can use the file object as an iterator. The iterator will return each line one by one, which can be processed. This will not read the whole file into memory and it’s suitable to read large files in Python.

我们可以使用文件对象作为迭代器。 迭代器将逐行返回每一行,可以对其进行处理。 这不会将整个文件读入内存,并且适合用Python读取大文件。

Here is the code snippet to read large file in Python by treating it as an iterator.

这是通过将Python视为迭代器来读取大型文件的代码段。

import resource
import osfile_name = "/Users/pankaj/abcdef.txt"print(f'File Size is {os.stat(file_name).st_size / (1024 * 1024)} MB')txt_file = open(file_name)count = 0for line in txt_file:# we can process file line by line here, for simplicity I am taking count of linescount += 1txt_file.close()print(f'Number of Lines in the file is {count}')print('Peak Memory Usage =', resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
print('User Mode Time =', resource.getrusage(resource.RUSAGE_SELF).ru_utime)
print('System Mode Time =', resource.getrusage(resource.RUSAGE_SELF).ru_stime)

When we run this program, the output produced is:

当我们运行该程序时,产生的输出为:

File Size is 257.4920654296875 MB
Number of Lines in the file is 60000000
Peak Memory Usage = 5840896
User Mode Time = 11.46692
System Mode Time = 0.09655899999999999

Python Read Large Text File

Python读取大文本文件

  • I am using os module to print the size of the file.我正在使用os模块来打印文件的大小。
  • The resource module is used to check the memory and CPU time usage of the program.资源模块用于检查程序的内存和CPU时间使用情况。

We can also use with statement to open the file. In this case, we don’t have to explicitly close the file object.

我们还可以使用with语句打开文件。 在这种情况下,我们不必显式关闭文件对象。

with open(file_name) as txt_file:for line in txt_file:# process the linepass

如果大文件没有行怎么办? (What if the Large File doesn’t have lines?)

The above code will work great when the large file content is divided into many lines. But, if there is a large amount of data in a single line then it will use a lot of memory. In that case, we can read the file content into a buffer and process it.

当将大文件内容分为多行时,以上代码将非常有用。 但是,如果一行中有大量数据,那么它将占用大量内存。 在这种情况下,我们可以将文件内容读入缓冲区并进行处理。

with open(file_name) as f:while True:data = f.read(1024)if not data:breakprint(data)

The above code will read file data into a buffer of 1024 bytes. Then we are printing it to the console.

上面的代码会将文件数据读取到1024字节的缓冲区中。 然后我们将其打印到控制台。

When the whole file is read, the data will become empty and the break statement will terminate the while loop.

当读取整个文件时,数据将变为空,并且break语句将终止while循环。

This method is also useful in reading a binary file such as images, PDF, word documents, etc.

此方法在读取二进制文件(例如图像,PDF,Word文档等)时也很有用。

Here is a simple code snippet to make a copy of the file.

这是制作文件副本的简单代码段。

with open(destination_file_name, 'w') as out_file:with open(source_file_name) as in_file:for line in in_file:out_file.write(line)

Reference: StackOverflow Question

参考 : StackOverflow问题

翻译自: https://www.journaldev.com/32059/read-large-text-files-in-python

python 读取文本文件

python 读取文本文件_如何在Python中读取大文本文件相关推荐

  1. cmd 文本文件分割,如何在Windows中分割大文本文件?

    I have a log file with size of 2.5 GB. Is there any way to split this file into smaller files using ...

  2. matlab分析xml文件_如何在Java中读取XML文件(DOM分析器)

    matlab分析xml文件 Today we will learn how to read the XML file in Java. We will also learn how to parse ...

  3. python中用什么函数读取字符串_如何在Python中获得函数名作为字符串?

    在Python中,如何在不调用函数的情况下以字符串的形式获得函数名? 1 2 3 4def my_function(): pass print get_function_name_as_string( ...

  4. python 线性回归模型_如何在Python中建立和训练线性和逻辑回归ML模型

    python 线性回归模型 Linear regression and logistic regression are two of the most popular machine learning ...

  5. unbantu上python安装步骤_如何在Ubuntu中安装Python 3.6?

    Python是增长最快的主要通用编程语言.原因有很多,比如它的可读性和灵活性,易于学习和使用,可靠和高效. 有两个主要的Python版本被使用- 2和3 (Python的现在和未来);前者将看不到新的 ...

  6. python进程暂停_如何在Python中暂停多进程?

    我希望用户能够在怎么开始的实现它?在 我的代码是:# -*- coding: utf-8 -*- from PySide import QtCore, QtGui from Ui_MainWindow ...

  7. python 拟合正态分布_如何在Python中拟合双高斯分布?

    我试图使用Python获得数据(link)的双高斯分布.原始数据的格式为: 对于给定的数据,我想获得图中所示峰值的两个高斯分布.我用以下代码(source)进行了尝试:from sklearn imp ...

  8. python 字节流分段_如何在Python中编写简单代码,并且速度超越Spark?

    全文共 3482字,预计学习时长 7分钟 如今,大家都在Python工具(pandas和Scikit-learn)的简洁性.Spark和Hadoop的可扩展性以及Kubernetes的操作就绪之间做选 ...

  9. python 概率分布函数_如何在Python中实现这五类强大的概率分布

    匿名用户 1级 2016-04-25 回答 首页 所有文章 观点与动态 基础知识 系列教程 实践项目 工具与框架应用 工具资源 伯乐在线 > Python - 伯乐在线 > 所有文章 &g ...

最新文章

  1. 一个老产品的心路历程
  2. 凯立德手机导航APP全新升级 小长假结伴出行说走就走
  3. 笔记本自开wifi设置
  4. mysql 调用未定义函数_php – Wierd和Annoying错误:调用未定义的函数mysql_query()[复制]...
  5. mysql 磁盘i o 优化_经典案例:磁盘I/O巨高排查全过程
  6. C++学习之路 | PTA乙级—— 1040 有几个PAT (25 分)(精简)
  7. 又一所“国字头”大学要来?屠呦呦也在
  8. Windows 下的批处理脚本基础——网络相关命令(用户操作命令、用户组操作命令)
  9. Spring Mvc 入门Demo
  10. python论文参考文献名称_Word的正确打开方式(附毕业论文模板)
  11. HTML+CSS实现弹跳球效果
  12. Android下将图片载入到内存中
  13. G - 罐子和硬币 (思维题)
  14. 数字IC设计学习笔记_专业书单整理
  15. 嵌入式linux ucgui,四、嵌入式之图形界面 (3) uCGui
  16. 教育部更新学科目录!考研(与在读)的同学都需要知道!
  17. cam_lidar_calib激光雷达和相机联合标定
  18. java 工厂模式例子_java 工厂模式简单介绍及例子
  19. Linux下的SD卡分区--解决sd卡分区损坏
  20. 魅族手机无限网无法连接服务器,魅族手机wifi为何连接不了了

热门文章

  1. 语音信号处理基础(四)—语音编辑
  2. [转载] Python中Numpy基础
  3. 排序类问题度量指标:Recall , MAP,MRR
  4. Linux中的nc测试端口是否开放
  5. 流式计算storm应用场景简介
  6. sql server 小技巧(8) visual studio 2013里使用Sql server compact 4.0及发布问题处理
  7. 解析C#中[],List,Array,ArrayList的区别及应用
  8. SQLServer的本月统计和本周统计
  9. Scala学习小小总结
  10. Struts1.x多文件上传问题