Friday, June 21, 2024

File Handling: Reading from and writing to files, handling different file types (text, CSV, JSON).

File Handling: Reading from and Writing to Files

File Handling: Reading from and Writing to Files

File handling is an essential part of programming, allowing you to read data from files, write data to files, and work with different file types such as text, CSV, and JSON. In this blog post, we will explore how to handle file operations in various formats.

Reading from Text Files

To read from a text file in Python, you can use the open() function with the read() method. Here is an example:

with open('example.txt', 'r') as file: data = file.read() print(data)

This code snippet opens a file named example.txt in read mode and reads its contents. The with statement ensures that the file is properly closed after reading.

Writing to Text Files

Similarly, you can write data to a text file using the write() method. Here is an example:

with open('output.txt', 'w') as file: file.write('Hello, World!')

This code snippet creates a new file named output.txt and writes the text Hello, World! to it.

Handling CSV Files

CSV (Comma-Separated Values) files are commonly used for storing tabular data. You can use the csv module in Python to read and write CSV files. Here is an example:

import csv with open('data.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)

This code snippet reads data from a CSV file named data.csv and prints each row of the file.

Working with JSON Files

JSON (JavaScript Object Notation) files are used for storing structured data. You can use the json module in Python to read and write JSON files. Here is an example:

import json data = {'name': 'Alice', 'age': 30} with open('data.json', 'w') as file: json.dump(data, file) with open('data.json', 'r') as file: data = json.load(file) print(data)

This code snippet creates a JSON file named data.json with a dictionary object, and then reads and prints the data from the file.

Common Use Cases

File handling is commonly used for tasks such as reading configuration files, processing log files, and saving application data. It is an important skill for any programmer, as it allows you to interact with external files and data sources.

Importance in Interviews

Understanding file handling is a common interview question for software development roles. Interviewers often ask candidates to write code that reads from or writes to a file, demonstrating their ability to work with external data sources.

Conclusion

File handling is a fundamental aspect of programming, allowing you to work with different file types and perform essential data operations. By mastering file handling techniques, you can enhance your programming skills and tackle a wide range of real-world tasks.

Tags: file handling, read from file, write to file, text files, CSV files, JSON files