0% found this document useful (0 votes)
14 views2 pages

File Handling and Data Persistence

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 2

File Handling and Data Persistence

File handling is an essential aspect of programming that allows applications to read


from and write to files stored on disk. In Python, this is accomplished using built-in
functions and methods, enabling developers to manage various file formats, including
text and CSV files.

Reading from Files


To read from a file in Python, you first need to open the file using the open() function.
This function takes two arguments: the file path and the mode (e.g., 'r' for reading).
Here's an example of reading a text file:
with open('example.txt', 'r') as file:
content = file.read()
print(content)

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.

Working with CSV Files


CSV (Comma-Separated Values) files are a common format for storing tabular data.
Python provides the csv module to handle CSV files easily. Here’s how to read from a
CSV file:
import csv

with open('data.csv', 'r') as file:


reader = csv.reader(file)
for row in reader:
print(row)
The csv.reader object allows you to iterate over each row in the CSV file. To write to a
CSV file, use the csv.writer:
import csv

with open('data_output.csv', 'w', newline='') as file:


writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 30, 'New York'])

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.

You might also like