python - 为什么在运行python脚本时收到“关闭文件”消息?

原文 标签 python file

why am I getting a 'closed file' message when I run my python script?

simple bit of code, just prints out a list of urls I put into a text file (it was printing them with the \n char at the end of each one though - how do I get rid of the \n?):

import mechanize, fileinput

with open('F:\Python\url_list2.txt') as urls:
    content = urls.readlines()
print content

anyway, it worked printed out the list, great. Run it again and I get this message in the python shell:

<closed file 'F:\Python\url_list2.txt', mode 'r' at 0x0000000002E4E390>

What is going on? Using windows 7 x64 if that makes any difference?

Answer

The with statement automatically closes the handle after all the statements inside it execute. If you need access to the handle afterwards:

import mechanize, fileinput

urls = open('F:\Python\url_list2.txt')
content = urls.readlines()
print content

If you want to get rid of the \n at the end of every line, use .strip():

import mechanize, fileinput

urls = open('F:\Python\url_list2.txt')
content = [x.strip() for x in urls.readlines()]
print content

翻译

简单的代码,只是打印出我放入一个文本文件中的网址列表(它在每个网址的末尾都用\ n char打印它们-我如何摆脱\ n?):

import mechanize, fileinput

with open('F:\Python\url_list2.txt') as urls:
    content = urls.readlines()
print content


无论如何,它可以打印出列表,很好。再次运行它,我在python shell中收到此消息:

<closed file 'F:\Python\url_list2.txt', mode 'r' at 0x0000000002E4E390>


到底是怎么回事?使用Windows 7 x64是否有什么区别?
最佳答案
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
相关推荐

python - 使用python处理配置文件的用户友好方式吗?

python - PyOpenGL:渲染...好吧...真正的一切

python - 学习python并遇到第一个程序的麻烦

python - 导入GDK时出现问题

javascript - 如何像Javascript一样调用Python函数

python - python tarinfo权限位

python - Django syncdb错误

python - Python总和麻烦

python - 如果要构建自定义数据库,该怎么办? [关闭]

python - 对象继承和嵌套cmd