Skip to main content

File Handling in Python

File Handling in Python

File handling is an essential aspect of programming, enabling you to read from and write to files. Python provides built-in functions and modules to work with various file types, including text, JSON, and XML files. This section covers how to perform file operations for these formats.

9.1 Reading and Writing Text Files

Text files are the simplest type of files and can be handled using Python’s built-in open() function. You can use this function to read from or write to text files.

9.1.1 Reading Text Files

# Reading from a text file

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

In this example, the open() function is used to open a file named example.txt in read mode ('r'). The read() method reads the entire content of the file into a string, which is then printed.

9.1.2 Writing to Text Files

# Writing to a text file

with open('example.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("This is a text file.")

In this example, the file example.txt is opened in write mode ('w'). The write() method writes text to the file. If the file does not exist, it will be created. If it does exist, its content will be overwritten.

9.2 Reading and Writing JSON Files

JSON (JavaScript Object Notation) is a lightweight data interchange format. Python’s json module provides methods for reading from and writing to JSON files.

9.2.1 Reading JSON Files

import json

# Reading from a JSON file
with open('data.json', 'r') as file:
    data = json.load(file)
    print(data)

Here, json.load() reads the JSON content from data.json and converts it into a Python dictionary or list, depending on the structure of the JSON data.

9.2.2 Writing to JSON Files

import json

# Writing to a JSON file
data = {
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

with open('data.json', 'w') as file:
    json.dump(data, file, indent=4)

In this example, json.dump() writes the data dictionary to data.json. The indent=4 parameter formats the JSON data with an indentation of 4 spaces for better readability.

9.3 Reading and Writing XML Files

XML (eXtensible Markup Language) is used to store and transport data. Python provides several libraries for working with XML files, such as xml.etree.ElementTree.

9.3.1 Reading XML Files

import xml.etree.ElementTree as ET

# Reading from an XML file
tree = ET.parse('data.xml')
root = tree.getroot()

for child in root:
    print(child.tag, child.attrib)

In this example, ET.parse() loads the XML file data.xml, and getroot() retrieves the root element of the XML tree. The code then iterates through the child elements of the root and prints their tags and attributes.

9.3.2 Writing to XML Files

import xml.etree.ElementTree as ET

# Creating XML data
data = ET.Element("data")
item = ET.SubElement(data, "item")
item.set("name", "Item1")
item.text = "This is item 1"

# Writing to an XML file
tree = ET.ElementTree(data)
tree.write('data.xml')

This example creates an XML structure with a root element data and a child element item. The ET.ElementTree() class is used to write the XML data to data.xml.

fficiently handle file-based data in your Python programs.

Comments

Popular posts from this blog

Arrays, Lists, and LinkedLists in Java

Arrays, Lists, and LinkedLists in Java Understanding the differences between arrays, lists, and linked lists is fundamental in Java programming. Each data structure has its unique characteristics and use cases. This guide will delve into how these structures work, their advantages and disadvantages, and provide examples of how to use them in Java. 1. Arrays in Java An array is a fixed-size data structure that stores elements of the same type in contiguous memory locations. Arrays are one of the simplest and most commonly used data structures in Java. 1.1 Declaring and Initializing Arrays You can declare and initialize an array as follows: public class ArrayExample { public static void main(String[] args) { // Declaration and initialization int[] numbers = new int[5]; // Array of integers with size 5 numbers[0] = 10; numbers[1] = 20...

Guide to Creating and Executing C Executables with Shared Libraries and Java Integration

Guide to Creating and Executing C Executables with Shared Libraries and Java Integration 1. Compiling a C Program to an Executable Step 1: Write a C Program #include <stdio.h> int main() { printf("Hello, World!\\n"); return 0; } Step 2: Compile the C Program gcc -o example example.c 2. Executing the C Program in the Console Step 3: Run the Executable ./example 3. Including Shared .so Libraries Step 4: Create a Shared Library #include <stdio.h> void my_function() { printf("Shared Library Function Called!\\n"); } gcc -shared -o libmylib.so -fPIC mylib.c Step 5: Update the C Program to Use the Shared Library #include <stdio.h> void my_function(); int main() { my_function(); printf("Hello, World!\\n...

Mastering Java Maps

In Java, maps are a versatile and powerful data structure that allow for the efficient storage and retrieval of key-value pairs. This document will cover various aspects of using maps in Java, from basic operations to advanced use cases. Overview of Maps Maps are part of the Java Collections Framework and provide a way to store data in key-value pairs. The keys are unique, and each key maps to exactly one value. Maps are crucial for tasks where quick lookups, insertions, and deletions are needed. Types of Maps Java provides several implementations of the Map interface, each with different characteristics: HashMap: Stores key-value pairs in a hash table. It does not guarantee any order of its elements. It allows one null key and multiple null values. LinkedHashMap: Extends HashMap and maintains a doubly-linked...