WEEK 8: Reading and Writing Files - M199205zn/IAS-CS4 GitHub Wiki

Basic File System Manipulation in Python: Reading and Writing Files

Python provides built-in functions to read and write files, making file system manipulation straightforward. The open() function is primarily used for handling files, allowing various modes such as reading, writing, and appending.


1. Opening a File

Before reading or writing a file, it must be opened using the open() function.

file = open("example.txt", "r")  # Open file in read mode

The open() function takes two parameters:

  • Filename (e.g., "example.txt")
  • Mode (e.g., "r" for reading)

Modes in open()

Mode Description
"r" Read mode (default); file must exist
"w" Write mode; creates file if it doesn’t exist, overwrites if it does
"a" Append mode; adds data to an existing file
"r+" Read and write mode
"w+" Read and write mode; overwrites file
"a+" Read and append mode

2. Writing to a File

To write to a file, use the "w" or "a" mode along with write() or writelines().

Example: Writing to a File

with open("example.txt", "w") as file:
    file.write("Hello, world!\n")
    file.write("This is a sample text file.")
  • write(): Writes a single string to the file.
  • writelines(): Writes multiple lines from a list.

Example: Writing Multiple Lines

lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example.txt", "w") as file:
    file.writelines(lines)

3. Reading from a File

To read a file, use the "r" mode with read(), readline(), or readlines().

Example: Reading the Entire File

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

Example: Reading Line by Line

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())  # strip() removes extra spaces or newline characters

Example: Reading Specific Lines

with open("example.txt", "r") as file:
    first_line = file.readline()  # Reads one line
    all_lines = file.readlines()  # Reads all lines into a list

4. Appending to a File

To add data without overwriting, use "a" mode.

with open("example.txt", "a") as file:
    file.write("\nThis is a new line appended to the file.")

5. Closing a File

It is important to close a file after operations to free system resources. Using with open() automatically handles this.

file = open("example.txt", "r")
content = file.read()
file.close()  # Manually closing the file

However, using with open() is the preferred approach since it automatically closes the file.


6. File Existence Check

To avoid errors when opening a file, check if it exists using os.path.exists().

import os

if os.path.exists("example.txt"): with open("example.txt", "r") as file: print(file.read()) else: print("File does not exist.")


7. Deleting a File

Use the os module to remove a file.

import os

if os.path.exists("example.txt"): os.remove("example.txt") print("File deleted.") else: print("File not found.")


Conclusion

Python makes file handling simple with built-in functions for reading, writing, appending, and deleting files. Using with open() ensures proper resource management. Understanding these basics is essential for working with file-based applications.

You can also make one involving structured data like JSON or CSV.

⚠️ **GitHub.com Fallback** ⚠️