Guide to High School Computer Science
  • 💻Introduction
    • windows & Python Development
    • macOS & Python Development
    • Visual Studio Code Settings
    • Set up Github
    • Author Page
  • 🧠Prerequisite Skills
    • Keyboard Typing
    • Files & Directories
    • Use of Command Line
    • Git & GitHub
    • Markdown
    • Starting Your Python Project
  • 🐍Python Programming
    • 🍎Python Basics
      • What is Python?
      • Procedural Programming & Programming Paradigms
      • String Formatting
      • Data Types
      • Input & Output to Console
      • Working with Numbers
      • Useful Built-in Functions
      • Math & Random Module
      • Boolean Data Object
      • Comparison, Logical, and Membership Operators
      • If Statements
      • Binary Decisions
      • Multiple Decisions
      • Nested Conditions
      • [EXTRA] Bitwise Operators
      • [EXTRA] Python Style Guide
    • ⏮️Iterations
      • Introduction to While Loops
      • Infinite Loop
      • Controlling Your While Loops
      • Introduction to For Loops
      • For Loops w/ Numeric Sequences
      • For Loops w/ Strings & Lists
      • Iterable Functions w/ For Loops
    • 📦Collections
      • Strings
        • String Basics
        • String Indexing
        • String Slicing
        • String Operators & Functions
        • Basic String Methods
        • String Methods Extended
        • String Methods Document
      • Tuples & Lists
        • Tuples
        • List Basics
        • List are Mutable
        • Adding Items to a List
        • Removing Items from a List
        • Search & Reverse a List
        • List Comprehension
        • List Methods Document
      • Sets
      • Dictionary
      • How to Store Multiple Data Items
    • 💡Defining Functions
      • Functions
      • print() vs return
      • Pre-determined Arguments
      • Nested Functions
      • Map & Filter
      • [Extra] Dynamic Arguments
    • 💾File I/O
      • How to Save Text to an External File
      • Reading CSV in Python
      • Reading JSON in Python
    • 🔨Basic Python Projects
      • Basic Calculator
        • Improving the calculator
        • Exercise Set 1
        • Exercise Set 2
        • 💎Streamlit Application #1
      • Basic Password Generator
        • Exercise Set 3
        • Exercises Related to Math
        • 💎Streamlit Application #2
      • A To-Do Task List
    • ⏳Introduction to Algorithmic Thinking
      • Big-O Notation
      • Basic Algorithms
        • Linear Search
        • Binary Search
        • Basic Sorting Algorithms
      • Recursion
      • Brute Force Algorithms
      • Greedy Algorithm
        • Time on Task (CCC 2013 J4)
        • Dijkstra’s Algorithm
      • Divide and Conquer
        • Merge Sort
      • Dynamic Programming
    • 🤯Object Oriented Programming
      • Class & Objects (Definitions)
      • OOP in Python
      • Encapsulation
      • Polymorphism
      • Inheritance & Overriding
      • Override Magic Methods
      • Case Study: 2D Vectors
      • Case Study: Deck of Cards
      • Exercise
      • Abstract Data Types
      • Case Study: Static 1D Array From Java
    • Competitive Programming
      • Is This Sum Possible?
        • Is the dataset sorted?
        • Searching for a value
        • Determine if the difference between an integer from the array and the target value exists
        • Sorting Algorithms
        • Using Two Pointers
      • Two Sum - LeetCode
        • Generate all possible pairs of values
        • Subtract each value from the target, see if the difference exists in the list
      • Longest Common Prefix - LeetCode
        • Compare all possible prefixes
        • Create the longest common prefix with the direct neighbour
      • Length of Last Word - LeetCode
        • Compare all possible prefixes
      • Where can I go from one point to another?
      • Sample Outline
    • IB Recipe Book
  • 💾Python & Databases
    • Intro to Databases & Data Modeling
      • Common Data Types in SQL
      • Introduction to ERDs
      • Primary Keys and Foreign Keys
      • Database Normalization
    • What is SQL?
      • Getting Started
      • SELECT Queries
        • Selection with Conditions
        • Selection with Fuzziness
        • Selection and Sorting in Order
        • Selection without Duplicates
        • Selection with Limited Number of Outputs
      • AGGREGATE Queries
        • Counting Rows
        • Sum, Average, Min/Max Queries
        • Working with Aggregate Queries
        • Power of using Groups
        • Exercise
      • Interacting with Multiple Table
      • Inserting Data
      • External Resource
  • ☕Java Essentials
    • Basics
      • Starting Java
      • Data & Variables
      • Handling User Inputs & Type Conversion
      • Arithmetic
      • IPO Model
      • Basic Built-in Methods
      • Exercise Questions
    • Conditionals
      • Boolean Operators
      • Compare Strings
      • If Statements
      • If Else Statements
      • Making Multiple Decisions
      • Using Switch
      • Flowchart Symbols
      • Exercise Questions
    • Iterations
      • While Loops
      • For Loop
      • Exercises
    • Java Type Casting
    • Strings
      • Common String Practices
      • String Formatting
      • Java Special Characters
    • Collection
      • Arrays
      • For Each Loop
      • ArrayList
      • Exercise Questions
    • Static Methods
      • (Aside) Clearing your Console
    • Randomness in Java
    • Delayed Output in Java
    • Java Output Formatting
    • Java Style Guide
  • 🛠️JavaScript Programming
    • Our Programming Editor & Workflow
      • Hello, world!
      • Commenting & Variables
      • Data in JavaScript
      • Operators
      • String Formatting
      • Getting User Input
    • JavaScript Exercise Set 1
    • Making Decisions
      • Comparing Values
      • Combining Boolean Comparisons
      • Creating Branches
    • JavaScript Exercise Set 2
    • While Loops
      • Infinite While Loop
      • While Loops and Numbers
      • While Loops and Flags
      • While loops w/ Strings
    • JavaScript Exercise Set 3
    • Subprograms & Functions
      • Creating a Function in JavaScript
      • Function with Input and Assignable Output
    • JavaScript Exercise Set 4
  • 💾Topics in CS
    • Computer Environments & Systems
      • Computer Components
        • In-depth Explanations
      • File Maintenance
      • Computer & Safety
      • Software Development
      • Bits & Binary
    • Careers related to Computer Science
    • Postsecondary Opportunities
Powered by GitBook
On this page
  • Goal
  • Important Definitions
  • A Starting Point for our Code
  • Adding the feature to save the database
  • Program's Terminal Output + Example Run
  • Contents of database.txt
  • Connected Reading
  1. Python Programming
  2. File I/O

How to Save Text to an External File

Goal

We want to save text data to an external file.

This is when we would want a persistent storage. Persistent storage is when we have our data saved and remembered even if our program is done executing.

Important Definitions

Reading

The term reading is the ability to obtain data from a file or an input source

Writing

The term writing is the ability to insert data to a file, and create a new content

Append

The term append is the ability to add new content to a data file without erasing the content within the file

A .txt file

A .txt file is a computer's simplest way to save written content. It is supported by many operating systems, and it does not worry about any type of formatting or design choices (such as font, colour, and font-sizes).

A Starting Point for our Code

This example code will track customer's phone models to have a related data of a customer having a customer number, customer's name, and their phone's maker (aka Apple or Google).

# Database Initialization
customers = {} # Empty Dictionary to Store customer data

# Initialize our database size
customer_count = int(input("How many customers: "))

# Based on the the number of users, we will add related user data to the dictionary
for i in range(customer_count):
    customer_key = f"Customer {i}"

    current_name = input(f"User {i}'s name: ")
    phone_company = input("Input user's Phone Maker: ")

    customers[customer_key] = [current_name, phone_company]

print("Our Database:")
print(customers)

Example Run (Added custom spacing below for readability)

The code creates a dictionary with the following features:

  • Key -> User's ID (Customer and their Number)

  • Value -> A simple list of string values with their name and the phone's make

How many customers: 3

User 0's name: Marshall
Input user's Phone Maker: Apple

User 1's name: Jasper
Input user's Phone Maker: Google

User 2's name: Freya
Input user's Phone Maker: Samsung

Our Database:
{
    'Customer 0': ['Marshall', 'Apple'], 
    'Customer 1': ['Jasper', 'Google'], 
    'Customer 2': ['Freya', 'Samsung']
}

The problem with the current code is that every time this code runs, it will create the dictionary during the program's execution and forget the database after the program stops running.

The simple/basic solution would be to store the contents of the dictionary into a text file.

Adding the feature to save the database

# Database Initialization
customers = {} # Empty Dictionary to Store customer data

# Initialize our database size
customer_count = int(input("How many customers: "))

# Based on the the number of users, we will add related user data to the dictionary
for i in range(customer_count):
    customer_key = f"Customer {i}"

    current_name = input(f"User {i}'s name: ")
    phone_company = input("Input user's Phone Maker: ")

    customers[customer_key] = [current_name, phone_company]

print("Our Database:")
print(customers)

# Creating an external file with our database
# Each line will have the following:
#   Customer Number, Customer Name, Customer's Phone Make
# Example:
#   Customer 0, Marshall, Apple

# Step 1: Use the Python's design pattern for creating a new file

with open("database.txt", "w") as new_file:
    # This created a new file called: database.txt
    # We can interact with it in our code by working with the variable called "new_file"
    # The 2nd argument in open() called "w" means we are writing content into the file
    
    # Step 2: 
    # - loop through the dictionary's key and value
    # - format the content to the our desired way
    # - insert it into the txt file

    for key, value in customers.items():
        customer_name = value[0]
        customer_company = value[1]

        written_data = f"{key}, {customer_name}, {customer_company}\n"
        # \n is a special instruction to say that we are adding a linebreak in our .txt file

        new_file.write(written_data)
    # end of for loop
    print("File creation finished.")
# When this code is finished, it will create a new database.txt at the same location of the python file

Program's Terminal Output + Example Run

How many customers: 2
User 0's name: Marshall
Input user's Phone Maker: Samsung
User 1's name: Freya
Input user's Phone Maker: Apple
Our Database:
{'Customer 0': ['Marshall', 'Samsung'], 'Customer 1': ['Freya', 'Apple']}
File creation finished.

Contents of database.txt

Customer 0, Marshall, Samsung
Customer 1, Freya, Apple

Connected Reading

PreviousFile I/ONextBasic Python Projects

Last updated 10 months ago

File Input / Output ()

Dictionary ()

List ()

🐍
💾
Link
Link
Link