Python Mastery – From Basics to Brilliance / File Handling

Real-Time Example: Saving Form Data to File

name = input("Enter your name: ")
email = input("Enter your email: ")

with open("form_data.txt", "a") as file:
    file.write(f"Name: {name}, Email: {email}\\n")

print("Form submitted successfully!")

🧠 What’s Happening Step-by-Step?

  1. Ask for user details:

    The program takes name and email from the user using input().

  2. Save the data in a file named form_data.txt:

    • The file is opened in append mode ("a"), so each new submission goes to a new line, without deleting previous entries.

  3. Write the details in a clean format:

    Name: Harsha, Email: harsha@example.com
  4. Confirmation message:

    Once saved, the user sees: Form submitted successfully!


🖨️ Sample Output:

Enter your name: Harsha
Enter your email: harsha@example.com
Form submitted successfully!

📂 What’s inside form_data.txt?

If 3 users submit the form, the file may look like:

Name: Harsha, Email: harsha@example.com
Name: Tisha, Email: tisha@gmail.com
Name: Ravi, Email: ravi123@yahoo.com

💡 Why append mode ("a")?

Because we want to keep all submissions, not overwrite the file each time.

Mode

Purpose

"w"

Write (overwrite old data)

"a"

Append (add to file)

"r"

Read from file


🔐 Bonus: Want to hide the file data from users?

Use .csv or .json format later for better structure and processing.