Lesson 1: File Input and Output
Learning Target
I can open, read, write, and append files in Python.
Opening and Reading Files
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Writing to Files
with open('example.txt', 'w') as file:
file.write('Hello, world!')
Appending to Files
with open('example.txt', 'a') as file:
file.write('\nAppended text')
Your Turn!
Write a program that:
- Creates a new file and writes some text to it
- Reads the content of the file and prints it
- Appends additional text to the file
Try it here:
Lesson 2: Checking and Deleting Files
Learning Target
I can check if a file exists and delete files in Python.
Checking if a File Exists
import os
if os.path.exists('example.txt'):
print('File exists')
else:
print('File does not exist')
Deleting Files
import os
if os.path.exists('example.txt'):
os.remove('example.txt')
print('File deleted')
Your Turn!
Write a program that:
- Checks if a file exists and prints a message
- Deletes the file if it exists
Try it here:
Lesson 3: Using the 'with' Statement
Learning Target
I can use the 'with' statement for file operations in Python.
Using 'with' for File Handling
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Your Turn!
Write a program that:
- Uses the 'with' statement to open and read a file
- Prints the content of the file
Try it here:
Lesson 4: Console Input and Output
Learning Target
I can read input from the console and print formatted text in Python.
Reading Input from Console
name = input('Enter your name: ')
print('Hello, ' + name)
Printing Formatted Text
name = 'Alice'
age = 30
print('Name: {}, Age: {}'.format(name, age))
print(f'Name: {name}, Age: {age}')
Your Turn!
Write a program that:
- Asks the user for their name and age
- Prints a message with their name and age using formatted text
Try it here:
Lesson 5: Command-Line Arguments
Learning Target
I can use command-line arguments in Python.
Using Command-Line Arguments
import sys
if len(sys.argv) > 1:
print('Arguments:', sys.argv[1:])
else:
print('No arguments provided')
Your Turn!
Write a program that:
- Prints the command-line arguments provided to the script
Try it here: