Python


Chapter 4: File Handling and Input/Output


Introduction:

In the previous chapters, we explored Python's foundational elements, including control flow, functions, and data structures. Now, it's time to take our programming skills to the next level by understanding file handling and input/output (I/O) operations in Python. File handling allows us to interact with external files, while I/O operations enable us to process data from various sources and present results to users. In this chapter, we will learn how to read from and write to files, handle different file formats, and gain proficiency in handling input and output in Python.

File Handling and Input/Output4.1 Opening and Closing Files

Before we can read from or write to a file, we need to open it. Python provides a built-in function, `open()`, for this purpose. The `open()` function takes two arguments: the file name and the mode (read, write, append, etc.). Once we are done with the file, it's essential to close it using the `close()` method to free up resources.


4.1.1 Opening a File for Reading

Code

```python

# Opening a file in read mode

file_path = "data.txt"

file = open(file_path, "r")

```


4.1.2 Opening a File for Writing

Code

```python

# Opening a file in write mode

file_path = "output.txt"

file = open(file_path, "w")

```


4.1.3 Closing the File

Code

```python

# Closing the file

file.close()

```


4.2 Reading from Files

Python offers various methods to read data from files. The most common ones are:


4.2.1 Reading the Entire File

Code

```python

file_path = "data.txt"

with open(file_path, "r") as file:

    content = file.read()

    print(content)

```


4.2.2 Reading Lines from a File

Code

```python

file_path = "data.txt"

with open(file_path, "r") as file:

    lines = file.readlines()

    for line in lines:

        print(line)

```


4.3 Writing to Files

To write data to files, we use methods like `write()` and `writelines()`.


4.3.1 Writing to a File

Code

```python

file_path = "output.txt"

with open(file_path, "w") as file:

    file.write("Hello, World!")

```


4.3.2 Writing Lines to a File

Code

```python

file_path = "output.txt"

lines = ["Line 1", "Line 2", "Line 3"]

with open(file_path, "w") as file:

    file.writelines(lines)

```


4.4 File Handling Best Practices

When working with files, it's crucial to follow some best practices to ensure data integrity and efficiency:


- Always close files after using them to free up resources.

- Use the `with` statement to automatically close files when exiting the block.

- Verify if a file exists before attempting to open it using `os.path.exists()`.

- Handle exceptions when opening and reading from files using `try-except` blocks.


4.5 Standard Input and Output

Python provides ways to interact with users through the standard input (`stdin`) and standard output (`stdout`). The `input()` function allows users to input data, while the `print()` function displays output to the console.


Code

```python

# Standard input

name = input("Enter your name: ")

print("Hello, " + name)

```

File Handling and Input/OutputConclusion

In this chapter, we explored the world of file handling and input/output operations in Python. Understanding how to read from and write to files is essential for many real-world applications, such as data analysis, log processing, and data persistence. Additionally, mastering standard input and output enables us to interact with users effectively. As we progress further, we'll continue to expand our Python toolkit and explore more advanced topics. In the next chapter, we'll venture into the fascinating world of object-oriented programming (OOP) and learn how to create and use classes to organize our code efficiently. Happy coding!