File open: Is this bad Python style?

前端 未结 6 1943
庸人自扰
庸人自扰 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:56

    The code works exactly as you say it does, but it's bad style nevertheless. Your code relies on assumptions which may be true now, but won't always be true. It's not impossible that your code will be run in a situation where the file being opened and not close does matter. Is it really worth that risk just to save 1 or 2 lines of code? I don't think so.

提交回复
热议问题