CS50P - Lecture 6 - File I/O

3 min read 1 month ago
Published on Aug 01, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial provides a comprehensive guide to file input and output (I/O) in Python, as demonstrated in CS50P Lecture 6. We'll explore how to read from and write to files, manage data persistence, and handle various file formats, including CSV and image files. Understanding file I/O is crucial for developing applications that require data storage beyond temporary memory.

Chapter 1: Understanding File I/O

  • Definition of File I/O: File I/O refers to the process of reading from and writing data to files in a computer's storage. It allows programs to store information permanently rather than temporarily.
  • Why Use Files: Storing data in files allows for data persistence across program runs. Without files, all data would be lost once the program terminates.

Chapter 2: Working with Lists

  • Creating a List: Start by creating a list to store multiple pieces of information. For example:
    names = []
    
  • Collecting User Input: Use a loop to gather multiple names from users and append them to your list:
    for _ in range(3):
        name = input("What's your name? ")
        names.append(name)
    
  • Sorting and Printing Names: Sort the list alphabetically and print the names:
    for name in sorted(names):
        print(f"Hello, {name}")
    

Chapter 3: Writing to Files

  • Opening a File: Use the open function to create or open a file for writing. Specify the mode as 'w' for writing:
    with open("names.txt", "w") as file:
        file.write(name + "\n")
    
  • Appending to Files: If you want to add data without overwriting existing content, use 'a' for append mode:
    with open("names.txt", "a") as file:
        file.write(name + "\n")
    

Chapter 4: Reading from Files

  • Reading All Lines: Read names back from a file and print them:
    with open("names.txt", "r") as file:
        lines = file.readlines()
        for line in lines:
            print(line.strip())
    
  • Handling New Lines: Ensure that when writing to files, you add a newline character to separate entries.

Chapter 5: Using CSV Files

  • CSV Basics: CSV (Comma-Separated Values) files allow for structured data storage. Each line represents a record, with fields separated by commas.
  • Reading CSV Files: Use Python's built-in csv module to handle CSV files easily:
    import csv
    
    with open("students.csv", "r") as file:
        reader = csv.reader(file)
        for row in reader:
            print(f"{row[0]} is in {row[1]}")
    
  • Writing CSV Files: Similarly, write to CSV files using csv.writer:
    with open("students.csv", "a", newline='') as file:
        writer = csv.writer(file)
        writer.writerow([name, home])
    

Chapter 6: Advanced CSV Handling

  • Using DictReader and DictWriter: These allow for more readable code by using dictionaries instead of lists to represent rows:
    import csv
    
    with open("students.csv", "r") as file:
        reader = csv.DictReader(file)
        for row in reader:
            print(f"{row['name']} is from {row['home']}")
    
  • Writing with DictWriter:
    with open("students.csv", "a", newline='') as file:
        fieldnames = ['name', 'home']
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writerow({'name': name, 'home': home})
    

Chapter 7: Working with Image Files

  • Using Pillow for Images: The Pillow library allows manipulation of image files, including creating animated GIFs:
    from PIL import Image
    
    images = [Image.open(arg) for arg in sys.argv[1:]]
    images[0].save('animated.gif', save_all=True, append_images=images[1:], duration=200, loop=0)
    

Conclusion

In this tutorial, we've covered the essential aspects of file I/O in Python, including reading and writing to text and CSV files, and manipulating image files. Understanding these concepts is vital for developing applications that require data persistence. To further your learning, consider experimenting with file formats, exploring additional libraries, or implementing more complex data handling in your projects.