【发布时间】:2015-11-23 05:37:24
【问题描述】:
我正在 Python 中尝试正则表达式操作。但是,一旦我使用它,我就无法再次读取该文件。
f = codecs.open(filename, 'rU', 'utf-8')
#print f.read() works here
#printing the year
year = re.search(r'Popularity in (\w+)',f.read())
print year.group(1)
#now, this returns nothing !
print f.read()
我无法理解我在这里做错了什么。
【问题讨论】:
-
你在文件流的末尾,所以没有什么要读的了。读取文件时考虑使用
with语句关闭资源。 -
如何使用
with语句关闭资源?我只知道f.close()。 -
这是一个示例:
with open('myfile.txt') as f:然后缩进并执行所有文件操作。当解释器离开with语句下方缩进区域定义的范围时,它将为您关闭文件。欲了解更多信息:effbot.org/zone/python-with-statement.htm
标签: python regex python-2.7 io