Code Fellows 401
Day 03 Notes
Home
Reading
Read & Write Files in Python
Exceptions in Python
Videos
Read & Write Files in Python - Companion Video
Bookmark and Review
Reading and Writing Files in Python Quiz
Things I want to know more about
- Python provides several ways to read and write files, including the built-in open() function, the file object and the with statement.
- The open() function is used to open a file and returns a file object, which is used to read and write the file.
- To read a file, the file object’s read() method can be used, which reads the entire contents of the file as a string.
- To read specific content from the file, readline() or readlines() can be used.
- To write to a file, the write() method on a file object can be used, which writes the specified string to the file.
- It’s best practice to use the with statement when working with files, as it automatically takes care of closing the file after you’re done with it.
- Also, when reading or writing files, you need to specify the mode in which you want to open the file, such as ‘r’ for reading, ‘w’ for writing and ‘a’ for appending
- It’s important to handle any exception that can occur during the file operations using try-except block.