How do I read and write files in Python?
Use the built-in `open()` function to read and write files. Use modes like 'r' for reading and 'w' for writing, and remember to close the file afterward.
Reading and writing files in Python is a fundamental task that can be accomplished using the built-in open()
function. The open()
function takes two primary arguments: the filename and the mode. Common modes include:
'r'
for reading (default mode)'w'
for writing (overwrites existing content)'a'
for appending
To read a file, use:
with open('file.txt', 'r') as file:
content = file.read()
The with
statement is recommended for file handling, as it ensures proper closure of the file even if an error occurs. For writing to a file:
with open('file.txt', 'w') as file:
file.write('Hello, World!')
For large files, consider using readline()
or iterating over the file object to read line by line, which is more memory efficient. By mastering file I/O in Python, you can effectively manage data storage and retrieval in your applications.