Handling files is an essential aspect of programming. Whether you’re working on data analysis or building web applications, reading from and writing to files are common tasks. This guide will walk you through file input/output operations in Python using practical examples.
Opening Files
To work with files in Python, we need to open them first. The built-in open()
function takes two arguments - the filename (or path), and the mode. There are several modes available such as 'r', 'w', 'a', etc., but let's focus on these three core ones:
- ‘r’: Opens a file in read mode, used when only retrieving information. Raises an error if the file doesn’t exist.
file = open('example.txt', 'r')
- ‘w’: Opens a file in write mode, erasing its previous content. If it didn’t exist before, creates one.
file = open('new_file.txt', 'w')
- ‘a’: Appends to an existing file; otherwise, behaves similarly to ‘w’.
file = open('existing_file.txt', 'a')