File Handling and Data Persistence
File Handling and Data Persistence
File Handling and Data Persistence
Using the with statement ensures that the file is properly closed after its suite finishes,
even if an error occurs. The read() method reads the entire file into a string.
Alternatively, you can use readline() to read the file line by line or readlines() to read all
lines into a list.
Writing to Files
Writing to a file is similar to reading, but you need to open the file in write mode ( 'w').
This mode will overwrite the file if it exists. To append content without overwriting, use
the append mode ('a'). Here’s an example:
with open('output.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is a new line.")
This code creates a new file called output.txt and writes two lines of text to it. If you want
to ensure that you do not accidentally overwrite existing data, you can open the file in
read/write mode ('r+'), which allows both reading and writing.
This code creates a new CSV file and writes a header row followed by a data row. The
newline='' parameter prevents extra blank lines in the output file on Windows.
Conclusion
File handling and data persistence in Python provide the foundational tools necessary
for working with external data sources. By mastering file operations, including reading
and writing text and CSV files, developers can create applications that effectively
manage and manipulate data.