File open: Is this bad Python style?

前端 未结 6 1880
庸人自扰
庸人自扰 2021-01-17 17:18

To read contents of a file:

data = open(filename, \"r\").read()

The open file immediately stops being referenced anywhere, so the file obje

6条回答
  •  自闭症患者
    2021-01-17 17:47

    Just for the record: This is only slightly longer, and closes the file immediately:

    from __future__ import with_statement
    
    with open(filename, "r") as f:
        data = f.read()
    

提交回复
热议问题