File open: Is this bad Python style?

前端 未结 6 1742
庸人自扰
庸人自扰 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 18:01

    Even though it works as expected, I think it fails in two counts:

    1. Your code will not scale up seamlessly, because you are reading the entire file into memory, and this may or may not be necessarily what you want.
    2. According to the Zen of Python (try import this in the Python prompt to retrieve it) "explicit is better than implicit" and, by failing to explicitly close the file, you could confuse someone who, down the road, will be left with your code for maintenance.

    It really helps being explicit! Python encourages explicit style.

    Other than that, for a throwaway script, your style makes sense.

    Maybe you will benefit from this answer.

提交回复
热议问题