File Handling with Copilot Prompts
In real-world Python projects, you often need to work with files — reading data from files, saving data for later, or exchanging data with others.
Python makes file handling straightforward, and with Copilot, you can write these scripts even faster by describing what you want in a clear prompt.
Why Learn File Handling?
- Store data between program runs (e.g., save a score or user preferences).
- Process large data files (logs, datasets, text files).
- Interact with other systems via files (e.g., importing/exporting CSV or JSON).
Reading and Writing Text Files
The most basic file operations are reading and writing simple text files.
Prompt
1
# Write a Python script to read a file and print its contents
Example Copilot Suggestion
1 2 3 4 5 6 7
def read_file(filename): try: with open(filename, 'r') as f: contents = f.read() print(contents) except FileNotFoundError: print("File not found.")
Explanation
open(filename, 'r')
: Opens the file in read mode.with
: Automatically closes the file when finished (good practice).f.read()
: Reads the entire file as a single string.except FileNotFoundError
: Catches the error if the file doesn’t exist.
Practice Example
1
read_file("sample.txt")
If sample.txt
exists, it prints the contents. Otherwise, it shows "File not found."
Writing to a File
To save data to a file, you open it in write mode ('w'
).
Example
1 2 3 4
def write_file(filename, text): with open(filename, 'w') as f: f.write(text) print("Data written successfully.")
Explanation
'w'
: Overwrites the file if it exists. Creates a new file if it doesn't.f.write(text)
: Writes the given text to the file.
Practice Example
1
write_file("output.txt", "Hello, this is my first file written from Python!")
Working with CSV Files
CSV (Comma-Separated Values) files are commonly used to store tabular data, like spreadsheets.
Reading CSV
Prompt
1
# Write a Python script to read a CSV file and print each row
Copilot Suggestion
1 2 3 4 5 6 7 8 9 10
import csv def read_csv(filename): try: with open(filename, 'r', newline='') as csvfile: reader = csv.reader(csvfile) for row in reader: print(row) except FileNotFoundError: print("CSV file not found.")
Explanation
import csv
: Python’s built-in CSV module.csv.reader()
: Reads each row as a list.- Looping through
reader
: Prints each row in the file.
Writing CSV
Prompt
1
# Write a function to write a list of rows to a CSV file
Copilot Suggestion
1 2 3 4 5 6 7
import csv def write_csv(filename, data): with open(filename, 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerows(data) print("CSV file written successfully.")
Explanation
writerows(data)
: Writes a list of lists, each sublist becomes a row.
Practice Example
1 2 3 4 5 6 7
rows = [ ["Name", "Age", "City"], ["Alice", "30", "New York"], ["Bob", "25", "Los Angeles"] ] write_csv("people.csv", rows) read_csv("people.csv")
Working with JSON Files
JSON (JavaScript Object Notation) is widely used for storing structured data, especially when working with web APIs.
Writing JSON
Prompt
1
# Write a function to save a dictionary as a JSON file
Copilot Suggestion
1 2 3 4 5 6
import json def save_to_json(filename, data): with open(filename, 'w') as jsonfile: json.dump(data, jsonfile, indent=4) print("JSON file saved successfully.")
Explanation
import json
: Python’s built-in module for JSON handling.json.dump()
: Saves Python dictionary as a JSON file.indent=4
: Makes the JSON file nicely formatted and easy to read.
Practice Example
1 2 3 4 5 6 7 8
data = { "name": "John", "age": 28, "city": "Chicago", "skills": ["Python", "Data Analysis"] } save_to_json("profile.json", data)
Reading JSON
Example
1 2 3 4 5 6 7 8 9
import json def read_from_json(filename): try: with open(filename, 'r') as jsonfile: data = json.load(jsonfile) print(data) except FileNotFoundError: print("JSON file not found.")
Practice Example
1
read_from_json("profile.json")
Key Takeaways
- Use
open()
with'r'
for reading,'w'
for writing. - Always close files; using
with
does this automatically. - Use
csv
module for spreadsheet-like data. - Use
json
module for structured, nested data. - Copilot can generate full file-handling functions for you — start with a clear, specific prompt.
Mini Challenge
Prompt
1
# Write a function that appends a new line to an existing text file, creating it if it doesn't exist
Try generating it with Copilot and test by appending different messages.
Practice Exercises
- Write a function to count the number of lines in a text file.
- Create a function that loads a list of dictionaries from a JSON file.
- Write a function that saves user input (name and email) into a CSV file.
Extra Tips
- Test file-handling code carefully to avoid overwriting important files.
- Check for file existence using
try-except
blocks. - Start small: first print text to a file, then try reading it back.