V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Morriaty
V2EX  ›  Python

执行 py 脚本的时候,如果不显式的 close file,会有什么问题?

  •  
  •   Morriaty · 2017-05-26 17:57:50 +08:00 · 2028 次点击
    这是一个创建于 2525 天前的主题,其中的信息可能已经有所发展或是发生改变。

    目前有个大量上传图片的脚本,大致如下:

    for item in items:
        files = [("file", ("test.jpg", open(path, "rb"), "image/png")) for path in item["paths"]]
        resp = requests.post(url, files=files)
    

    由于这里使用了列表推导,所以没办法显式的 close 文件,with语句也没办法用。

    这里会有什么问题吗? 脚本执行结束,这些 file 会自动被 close 吗?

    3 条回复    2017-05-27 05:47:32 +08:00
    Morriaty
        1
    Morriaty  
    OP
       2017-05-26 18:08:37 +08:00
    dreamapple
        2
    dreamapple  
       2017-05-26 19:03:30 +08:00 via Android
    read ( r )无所谓的,write ( w )偶尔会写不到磁盘上吧
    而且每次你的列表推导执行会把上次的引用解引,系统会自动 close,也不用担心占用太多 fd 吧
    fuge
        3
    fuge  
       2017-05-27 05:47:32 +08:00
    with open as
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2667 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 00:03 · PVG 08:03 · LAX 17:03 · JFK 20:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.