本文翻译自:Reading entire file in Python

If you read an entire file with content = open('Path/to/file', 'r').read() is the file handle left open until the script exits? 如果你读取整个文件,其中content = open('Path/to/file', 'r').read()是文件句柄保持打开状态,直到脚本退出? Is there a more concise method to read a whole file? 是否有更简洁的方法来读取整个文件?


#1楼

参考:https://stackoom.com/question/V5ca/用Python读取整个文件


#2楼

You can use pathlib . 您可以使用pathlib 。

For Python 3.5 and above: 对于Python 3.5及更高版本:

from pathlib import Path
contents = Path(file_path).read_text()

For lower versions of Python use pathlib2 : 对于较低版本的Python,请使用pathlib2 :

$ pip install pathlib2

Then: 然后:

from pathlib2 import Path
contents = Path(file_path).read_text()

This is the actual read_text implementation : 这是实际的read_text 实现 :

def read_text(self, encoding=None, errors=None):"""Open the file in text mode, read it, and close the file."""with self.open(mode='r', encoding=encoding, errors=errors) as f:return f.read()

#3楼

The answer to that question depends somewhat on the particular Python implementation. 该问题的答案在某种程度上取决于特定的Python实现。

To understand what this is all about, pay particular attention to the actual file object. 要了解这是什么,请特别注意实际的file对象。 In your code, that object is mentioned only once, in an expression, and becomes inaccessible immediately after the read() call returns. 在您的代码中,该对象在表达式中仅被提及一次,并且在read()调用返回后立即变得不可访问。

This means that the file object is garbage. 这意味着文件对象是垃圾。 The only remaining question is "When will the garbage collector collect the file object?". 唯一剩下的问题是“垃圾收集器什么时候收集文件对象?”。

in CPython, which uses a reference counter, this kind of garbage is noticed immediately, and so it will be collected immediately. 在使用引用计数器的CPython中,会立即注意到这种垃圾,因此会立即收集它。 This is not generally true of other python implementations. 对于其他python实现,这通常不正确。

A better solution, to make sure that the file is closed, is this pattern: 为确保文件已关闭,更好的解决方案是这种模式:

with open('Path/to/file', 'r') as content_file:content = content_file.read()

which will always close the file immediately after the block ends; 在块结束后将立即关闭文件; even if an exception occurs. 即使发生异常。

Edit: To put a finer point on it: 编辑:为它添加一个更好的点:

Other than file.__exit__() , which is "automatically" called in a with context manager setting, the only other way that file.close() is automatically called (that is, other than explicitly calling it yourself,) is via file.__del__() . 除了file.__exit__() ,它在一个with上下文管理器设置的情况下“自动”调用, file.close()被自动调用的唯一另一种方式(也就是说,除了自己显式调用它之外)是通过file.__del__() This leads us to the question of when does __del__() get called? 这引出了我们__del__()何时被调用的问题?

A correctly-written program cannot assume that finalizers will ever run at any point prior to program termination. 正确编写的程序不能假定终结器将在程序终止之前的任何时刻运行。

-- https://devblogs.microsoft.com/oldnewthing/20100809-00/?p=13203 - https://devblogs.microsoft.com/oldnewthing/20100809-00/?p=13203

In particular: 特别是:

Objects are never explicitly destroyed; 对象永远不会被明确销毁; however, when they become unreachable they may be garbage-collected. 然而,当它们变得无法到达时,它们可能被垃圾收集。 An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable. 允许实现推迟垃圾收集或完全省略垃圾收集 - 只要没有收集到仍然可以访问的对象,实现垃圾收集的实现方式就是如此。

[...] [...]

CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. CPython目前使用带有(可选)延迟检测循环链接垃圾的引用计数方案,它会在大多数对象无法访问时立即收集,但不保证收集包含循环引用的垃圾。

-- https://docs.python.org/3.5/reference/datamodel.html#objects-values-and-types - https://docs.python.org/3.5/reference/datamodel.html#objects-values-and-types

(Emphasis mine) (强调我的)

but as it suggests, other implementations may have other behavior. 但正如它所暗示的那样,其他实现可能还有其他行为。 As an example, PyPy has 6 different garbage collection implementations ! 举个例子,PyPy 有6个不同的垃圾收集实现 !

用Python读取整个文件相关推荐

  1. python 读取excel文件 效率 时间 格式_python读取Excel文件中的时间数据

    在使用python读取Excel文件中的时间格式,碰到的时间格式转换问题: 读取这样的表格: 输出这样的数据结果: 然而这样的结果却不是我们想要的,我们需要的是这样的结果: 1.安装python官方库 ...

  2. python读取一个文件夹/子文件夹下的所有文件名字

    python读取一个文件夹/子文件夹下的所有文件名字 示例代码: import osfile_path = './images/' all_file_name = os.listdir(file_pa ...

  3. python删除重复值所在的行数_使用python读取txt文件的内容,并删除重复的行数方法...

    注意,本文代码是使用在txt文档上,同时txt文档中的内容每一行代表的是图片的名字. #coding:utf-8 import shutil readDir = "原文件绝对路经" ...

  4. python读取txt文件并画图

    1,使用python读取txt文件 已知txt文件内容如下: 0 01 12 43 94 165 256 36 请以第一列为x轴,第二列为y轴画图 步骤如下: 1)使用readlines读取文件 2) ...

  5. MATLAB和Python读取wave文件的波形对比

       用python读取.wav文件的波形后再用MATLAB读取文件波形进行验证. 1.MORSE 1.1 Python 程序见之前的博客. 波形如图1所示: 图1 1.2 MATLAB 读取波形程序 ...

  6. python怎么读xlsx_用python读取xlsx文件

    一 准备工作: 二 xlrd库读取 首先安装xlrd库,安装方法: pip install xlrd import xlrd #打开excel wb = xlrd.open_workbook('tes ...

  7. python读取.edf文件

    目录 EDF文件简介 MNE-python读取.edf文件 案例 第一步:导入工具包 第二步:加载本地edf文件 第三步:获取原始数据中事件 第四步:根据事件ID获取对应事件 第五步:绘制事件图 本教 ...

  8. python读取.locs文件

    目录 简介 知识点: 案例 本教程为脑机学习者Rose发表于公众号:脑机接口社区 .QQ交流群:903290195 简介 本案例主要介绍如何读取eeglab示例文件.locs文件.为了演示电极位置,所 ...

  9. python英文单词及其出现次数-Python读取英文文件并记录每个单词出现次数后降序输出示例...

    本文实例讲述了Python读取英文文件并记录每个单词出现次数后降序输出.分享给大家供大家参考,具体如下: 对文中出现的句号,逗号和感叹号做了相应的处理 sorted排序函数用法: 按照value值降序 ...

最新文章

  1. XML DTD 语言学习笔记
  2. 建立注册DLL和反注册DLL文件的快捷方式
  3. UIButton下面添加滑动的线
  4. Openstack启用spice协议
  5. 如何用 Cocos Creator 3D 如何实现小姐姐的发丝高光?
  6. python怎么改背景_python IDE背景怎么改
  7. C# 延时小函数 很好用
  8. UIWebView / NSURL / NSBoundle 相关应用 (实例,加载完成前的背景, 默认safari打开链接地址等)...
  9. [开源][J2ME]J2ME手机应用程序UI开发框架
  10. pycharm编程工具自带python环境吗_pycharm+PyQt5+python最新开发环境配置(踩坑)
  11. 路由器截获微信消息_猫(Modem)和路由器有什么区别?
  12. 外企程序员常用英语单词
  13. 使用PHP+Swoole实现的网页即时聊天工具:PHPWebIM
  14. 一、简单刷题APP(题库是Excel)之项目功能和效果图
  15. UINO优锘:DCV产品发展历程
  16. [Unity]Mesh Baker3.1.0使用教程
  17. xcel Home 数据透视表初级班(10118班)小结第二课时
  18. 中国电子学会图形化四级编程题:小猫钓鱼
  19. Java Web HTML基础 静态网页制作
  20. ChatGPT万能工具箱 | ChatGPT辅助神器 提升了用户体验 提问回答更加精确。

热门文章

  1. 如何安装fedora13的显卡驱动
  2. 算法--- 二叉树的右视图
  3. Android报错:java.lang.IllegalArgumentException: Surface was abandoned
  4. C语言函数集(十六)
  5. Android性能优化之电量篇(四)
  6. 减少资源消耗方法之一:减少状态图片
  7. 【Http专题】Https
  8. 对action/ 和 category/ 的理解
  9. 堆实战(动态数据流求top k大元素,动态数据流求中位数)
  10. SpringSecurity过滤器链汇总