-1

The solution to the following link did not solve my issue: How do I close a file object I never assigned to a variable?

How do I close the file in the following line?

file = open(filename, 'r').read().splitlines() 
Community
  • 1
  • 1
idealistikz
  • 1,247
  • 5
  • 21
  • 35
  • Why did it not solve your issue? – Thomas Jun 08 '12 at 19:17
  • 2
    Is there any reason as to why you want to avoid the `with` statement in this case (as per the last question)? It may not be on one line, but you don't have to worry about closing the file... – Makoto Jun 08 '12 at 19:17
  • The solution in the linked question actually is the best answer. See also http://stackoverflow.com/questions/10946134/in-python-how-can-i-open-a-file-and-read-it-on-one-line-and-still-be-able-to-c/10946193#10946193. – Sven Marnach Jun 08 '12 at 19:18
  • 1
    possible duplicate of [How do I close a file object I never assigned to a variable?](http://stackoverflow.com/questions/9426978/how-do-i-close-a-file-object-i-never-assigned-to-a-variable) – Sven Marnach Jun 08 '12 at 19:20
  • You rewrite the above code so you have access to the object to close it. Or use `with`. – Silas Ray Jun 08 '12 at 19:21
  • This is really a silly question. You already know how to close a file. So you're asking, "How can I deliberately avoid closing a file—but close it anyway?" Maybe the best answer is to write the correct code but then trick yourself into believing you wrote the incorrect code? – abarnert Jun 08 '12 at 22:25

1 Answers1

6

Such a file is automatically garbage collected and closed. However, this pattern should generally be avoided. Instead, use the with statement:

with open(filename, 'r') as fd:
    lines = fd.read().splitlines()
dbkaplun
  • 3,407
  • 2
  • 26
  • 33
  • 1
    I would avoid using `file` as a variable name. Other than that, this is a good answer. – Joel Cornett Jun 08 '12 at 19:25
  • 1
    Also, if you don't use `with` or if you don't explicitly `close()` a file object, It is not guaranteed to be garbage collected, especially if the script exits unexpectedly. – Joel Cornett Jun 08 '12 at 19:26
  • @JoelCornett - If the script exits unexpectedly, the process goes away, which implies that all open file descriptors will be closed. – twalberg Jun 08 '12 at 20:05
  • @twalberg: That's certainly not guaranteed by Python. Of course it's true on every modern desktop or server OS… but Python runs (or at least has run) on platforms (like Classic Mac), where open files don't get closed when a process goes away. – abarnert Jun 08 '12 at 22:23