推荐学习书目
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 · May 26, 2017 · 2737 views
    This topic created in 3334 days ago, the information mentioned may be changed or developed.

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

    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 replies    2017-05-27 05:47:32 +08:00
    dreamapple
        2
    dreamapple  
       May 26, 2017 via Android
    read ( r )无所谓的,write ( w )偶尔会写不到磁盘上吧
    而且每次你的列表推导执行会把上次的引用解引,系统会自动 close,也不用担心占用太多 fd 吧
    fuge
        3
    fuge  
       May 27, 2017
    with open as
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5472 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 06:58 · PVG 14:58 · LAX 23:58 · JFK 02:58
    ♥ Do have faith in what you're doing.