Skip to main content
The 2024 Developer Survey results are live! See the results
added 12 characters in body
Source Link
jamylak
  • 132.4k
  • 30
  • 235
  • 235

Note that: f.close doesn't do anythingactually close the file, you have to call the function: f.close()

To answer your question, the best way is using a with block. The file will be automatically closed even if an exception is raised:

with open('test.txt') as f:
    pass
# Automatically closes file on with block exit

Note that: f.close doesn't do anything, you have to call the function: f.close()

To answer your question, the best way is using a with block. The file will be automatically closed even if an exception is raised:

with open('test.txt') as f:
    pass
# Automatically closes file on with block exit

Note that: f.close doesn't actually close the file, you have to call the function: f.close()

To answer your question, the best way is using a with block. The file will be automatically closed even if an exception is raised:

with open('test.txt') as f:
    pass
# Automatically closes file on with block exit
added 70 characters in body
Source Link
jamylak
  • 132.4k
  • 30
  • 235
  • 235

Note that: f.close doesn't do anything, you have to call the function: f.close()

To answer your question, the best way is using a with block. The file will be automatically closed even if an exception is raised:

with open('test.txt') as f:
    pass
# Automatically closes file on with block exit

Note that: f.close doesn't do anything, you have to call the function: f.close()

To answer your question, the best way is using a with block:

with open('test.txt') as f:
    pass
# Automatically closes file on with block exit

Note that: f.close doesn't do anything, you have to call the function: f.close()

To answer your question, the best way is using a with block. The file will be automatically closed even if an exception is raised:

with open('test.txt') as f:
    pass
# Automatically closes file on with block exit
Source Link
jamylak
  • 132.4k
  • 30
  • 235
  • 235

Note that: f.close doesn't do anything, you have to call the function: f.close()

To answer your question, the best way is using a with block:

with open('test.txt') as f:
    pass
# Automatically closes file on with block exit