Skip to main content
added 265 characters in body
Source Link
Matt Adams
  • 719
  • 4
  • 11

Open files use resources and may be locked, preventing other programs from using them. Anyway, it is good practice to use with when reading files, as it takes care of closing the file for you.

with open('file', 'r') as f:
   read_data = f.read()

Here's an example of something "bad" that might happen if you leave a file open. Open a file for writing in your python interpreter, write a string to it, then open that file in a text editor. On my system, the file will be empty until I close the file handle.

Open files use resources and may be locked, preventing other programs from using them. Anyway, it is good practice to use with when reading files, as it takes care of closing the file for you.

with open('file', 'r') as f:
   read_data = f.read()

Open files use resources and may be locked, preventing other programs from using them. Anyway, it is good practice to use with when reading files, as it takes care of closing the file for you.

with open('file', 'r') as f:
   read_data = f.read()

Here's an example of something "bad" that might happen if you leave a file open. Open a file for writing in your python interpreter, write a string to it, then open that file in a text editor. On my system, the file will be empty until I close the file handle.

Source Link
Matt Adams
  • 719
  • 4
  • 11

Open files use resources and may be locked, preventing other programs from using them. Anyway, it is good practice to use with when reading files, as it takes care of closing the file for you.

with open('file', 'r') as f:
   read_data = f.read()