为什么运行Python脚本时会收到“文件已关闭”的消息?
这段简单的代码只是把我放在文本文件里的网址打印出来(不过它在每个网址后面加了个\n字符,我想知道怎么去掉这个\n)。
import mechanize, fileinput
with open('F:\Python\url_list2.txt') as urls:
content = urls.readlines()
print content
总之,它成功地打印出了网址列表,太好了。再运行一次,我在Python的命令行里收到了这个消息:
<closed file 'F:\Python\url_list2.txt', mode 'r' at 0x0000000002E4E390>
这是怎么回事?我在使用Windows 7 x64,如果这有什么影响的话。
6 个回答
2
试着打印内容(网址在关闭后就消失了。)
3
with
语句只在缩进的代码块内保持文件打开。你可以试试:
import mechanize, fileinput
with open('F:\Python\url_list2.txt') as urls:
content = urls.readlines()
print urls # file still open.
print content
基本上,with 是一种简化写法,用来处理常见的 try except finally
模式:
try:
urls = open('F:\Python\url_list2.txt')
# rest of indented block
finally:
urls.close()
# stuff outside of indented block
所以你的代码实际上变成了:
import mechanize, fileinput
try:
urls = open('F:\Python\url_list2.txt')
# rest of indented block
content = urls.readlines()
finally:
urls.close()
# stuff outside of indented block.
print urls
所以你会明白为什么你的 urls 被报告为已关闭的文件……因为你在退出 with
的缩进块时就关闭了它。你可能想要 print content
来查看你从已关闭的 urls
文件中加载到变量里的 content
。
0
with
语句会在里面的所有代码执行完后,自动关闭文件的连接。如果你之后还想用这个连接:
import mechanize, fileinput
urls = open('F:\Python\url_list2.txt')
content = urls.readlines()
print content
如果你想去掉每行末尾的 \n
(换行符),可以使用 .strip()
:
import mechanize, fileinput
urls = open('F:\Python\url_list2.txt')
content = [x.strip() for x in urls.readlines()]
print content