Python文件Slurp [英] Python File Slurp

查看:172
本文介绍了Python文件Slurp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以读取Python中所有文件的行,而不是标准:

  f = open('x.txt')
cts = f.read()
f.close()

似乎这样做经常发生,所以必须有一个单线。任何想法?

解决方案

这将在Python 2.6 1 及以上:

  with open('x.txt')as x:f = x.read()

这将创建一个行列表:

  with open('x.txt')as x:f = x.readlines()

这些方法保证了在读取之后立即关闭输入文件。



脚注:


  1. 此方法也可以在Python 2.5中使用,使用__future__ import with_statement 中的






不保证立即关闭的旧方法是使用它来创建一个字符串:

  f = open('x.txt')。read()


$ b


f = open('x.txt')。readlines()

实际上它会立即在某些版本的CPython中关闭,但是只有当垃圾收集器在Jython,IronPython和CPython的未来版本中都可以获得它。


Is there a one-liner to read all the lines of a file in Python, rather than the standard:

f = open('x.txt')
cts = f.read()
f.close()

Seems like this is done so often that there's got to be a one-liner. Any ideas?

解决方案

This will slurp the content into a single string in Python 2.61 and above:

with open('x.txt') as x: f = x.read()

And this will create a list of lines:

with open('x.txt') as x: f = x.readlines()

These approaches guarantee immediate closure of the input file right after the reading.

Footnote:

  1. This approach can also be used in Python 2.5 using from __future__ import with_statement.


An older approach that does not guarantee immediate closure is to use this to create a single string:

f = open('x.txt').read()

And this to create a list of lines:

f = open('x.txt').readlines()

In practice it will be immediately closed in some versions of CPython, but closed "only when the garbage collector gets around to it" in Jython, IronPython, and probably some future version of CPython.

这篇关于Python文件Slurp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆