Files are central to many operations in programming, be it for configuration, data storage, or data analysis. Python provides a built-in file handling system that allows developers to read from and write to files seamlessly.
The open()
Function: The primary way to work with files is using the open()
function. It returns a file object, and it is most commonly used with two arguments – the filename and the mode.
file = open('example.txt', 'r')
File Modes:
'r'
: Read (default). Opens the file for reading.'w'
: Write. Opens the file for writing (creates a new file or truncates an existing file).'a'
: Append. Opens the file for writing (creates a new file or appends to an existing file).'b'
: Binary mode. Reads or writes the file in binary mode.'x'
: Exclusive creation. Creates a new file but raises an error if the file already exists.'rb'
or 'w+'
.Reading Entire Content: The read()
method reads the content of the file into a string.
content = file.read()
print(content)
Reading Line-by-Line: The readline()
method reads a single line from the file.
line = file.readline()
print(line)
Alternatively, you can iterate through the file object itself for line-by-line reading:
for line in file:
print(line)
The write()
Method: This method writes a string to the file.
file = open('example.txt', 'w')
file.write("Hello, World!")
Note: This will overwrite the content if the file already exists.
Appending to Files: To add content to an existing file without overwriting, use the append mode ('a'
).
file = open('example.txt', 'a')
file.write("\nAppended Text.")
Always remember to close your files to free up resources and ensure that changes are flushed to disk.
file.close()
with
StatementsA more elegant way to handle files, which takes care of closing the file automatically, is the with
statement.
with open('example.txt', 'r') as file:
content = file.read()
print(content)
With the with
statement, the file is automatically closed once the block inside is exited.
File operations are a core aspect of many applications. Whether you’re reading configuration data, storing user-generated content, or processing large datasets, understanding how to efficiently and safely handle files in Python is essential. Always ensure to handle exceptions (like FileNotFoundError
) and manage resources by closing files after use or using the with
statement.