现在我使用:
pageHeadSectionFile = open('pagehead.section.htm','r')
output = pageHeadSectionFile.read()
pageHeadSectionFile.close()
Run Code Online (Sandbox Code Playgroud)
但为了使代码看起来更好,我可以这样做:
output = open('pagehead.section.htm','r').read()
Run Code Online (Sandbox Code Playgroud)
使用上述语法时,如何关闭文件以释放系统资源?
Tim*_*ker 171
您不必关闭它 - Python将在垃圾收集期间或程序退出时自动执行此操作.但正如@delnan指出的那样,出于各种原因明确关闭它是更好的做法.
那么,你可以做些什么来保持简短,明确:
with open('pagehead.section.htm','r') as f:
output = f.read()
Run Code Online (Sandbox Code Playgroud)
我认为现在它只有两行而且非常易读.
Jan*_*zny 44
Path('pagehead.section.htm').read_text()
Run Code Online (Sandbox Code Playgroud)
别忘了导入路径:
jsk@dev1:~$ python3
Python 3.5.2 (default, Sep 10 2016, 08:21:44)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pathlib import Path
>>> (Path("/etc") / "hostname").read_text()
'dev1.example\n'
Run Code Online (Sandbox Code Playgroud)
在Python 27上安装backported pathlib
或pathlib2
Sve*_*ach 19
使用CPython,您的文件将在执行该行后立即关闭,因为文件对象会立即被垃圾回收.但有两个缺点:
在与CPython不同的Python实现中,文件通常不会立即关闭,而是在以后的时间内,超出您的控制范围.
在Python 3.2或更高版本中ResourceWarning
,如果启用,将抛出一个.
最好再投资一条线:
with open('pagehead.section.htm','r') as f:
output = f.read()
Run Code Online (Sandbox Code Playgroud)
这将确保在所有情况下正确关闭文件.
SDs*_*lar 13
无需导入任何特殊库来执行此操作.
使用普通语法,它将打开文件进行读取然后关闭它.
with open("/etc/hostname","r") as f: print f.read()
Run Code Online (Sandbox Code Playgroud)
要么
with open("/etc/hosts","r") as f: x = f.read().splitlines()
Run Code Online (Sandbox Code Playgroud)
它给你一个包含线条的数组x,可以这样打印:
for line in x: print line
Run Code Online (Sandbox Code Playgroud)
你可以做的是使用with
声明:
>>> with open('pagehead.section.htm', 'r') as fin: output = fin.read();
>>> print(output)
some content
Run Code Online (Sandbox Code Playgroud)
即使代码中发生了不好的事情,该with
语句也会注意调用__exit__
给定对象的函数; 它接近try... finally
语法.对于返回的对象open
,__exit__
对应于文件关闭.
Python 2.6引入了这个语句.
使用ilio :(内联io):
只有一个函数调用而不是文件open(),read(),close().
from ilio import read
content = read('filename')
Run Code Online (Sandbox Code Playgroud)
我认为实现这一点最自然的方法是定义一个函数。
def read(filename):
f = open(filename, 'r')
output = f.read()
f.close()
return output
Run Code Online (Sandbox Code Playgroud)
然后您可以执行以下操作:
output = read('pagehead.section.htm')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
147120 次 |
最近记录: |