Python
Chapter 4: File Handling and Input/Output
Introduction:
4.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)
```
Conclusion
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!
0 Comments