Lesson 19 of 55 · Python
File I/O
Duration: 20 minutes
Lesson 19 of 55 · Python
Duration: 20 minutes
open() function, especially when used inside a with context manager.\n\npython\n# Write to a file\nwith open('example.txt', 'w') as f:\n f.write('First line\nSecond line')\n\n# Read the whole file\nwith open('example.txt', 'r') as f:\n content = f.read()\n print(content)\n\n\nThe with block guarantees that the file is properly closed, even if an error occurs inside the block.\n