Python · Syntax · Beginner
Working with files: reading and writing
Hands-on exercises for working with files in Python: reading text, writing lines, appending data, counting lines and words, processing file contents, and creating simple reports.
Quick topic start and explanations before exercises (exercises below):
Writing and appending
#File processing patterns
#File operations quick reference
#Exercises:
Read the entire file.
#Create a file note.txt with the text "Python files". Then open this file for reading, read all its contents, and print it to the terminal.
file_name = "note.txt"
Solution
file_name = "note.txt"
with open(file_name, "w", encoding="utf-8") as file:
file.write("Python files")
with open(file_name, "r", encoding="utf-8") as file:
text = file.read()
print(text)
Write a string to a file.
#The user enters one string. Write this string to the file message.txt, then read the file and print its contents.
text = input("Enter a message: ")
file_name = "message.txt"
Solution
text = input("Enter a message: ")
file_name = "message.txt"
with open(file_name, "w", encoding="utf-8") as file:
file.write(text)
with open(file_name, "r", encoding="utf-8") as file:
result = file.read()
print(result)
Add a line to the end of a file.
#The file log.txt already contains the line "Start". The user enters a new line. Add it to the end of the file on a new line and print the final contents of the file.
file_name = "log.txt"
with open(file_name, "w", encoding="utf-8") as file:
file.write("Start")
new_line = input("New line: ")
Solution
file_name = "log.txt"
with open(file_name, "w", encoding="utf-8") as file:
file.write("Start")
new_line = input("New line: ")
with open(file_name, "a", encoding="utf-8") as file:
file.write("\n" + new_line)
with open(file_name, "r", encoding="utf-8") as file:
text = file.read()
print(text)
Count lines in a file.
#Create a file tasks.txt with three lines: "Learn", "Practice", "Repeat". Read the file and print the number of lines.
file_name = "tasks.txt"
Solution
file_name = "tasks.txt"
with open(file_name, "w", encoding="utf-8") as file:
file.write("Learn\nPractice\nRepeat")
with open(file_name, "r", encoding="utf-8") as file:
lines = file.readlines()
print("Number of lines:", len(lines))
# or like this: count lines in a loop
file_name = "note.txt"
count = 0
with open(file_name, "r", encoding="utf-8") as file:
for line in file:
count += 1
print(count)
Find the longest word.
#Create a file words.txt with words separated by spaces: "code python file student". Read the file and print the longest word.
file_name = "words.txt"
Solution
file_name = "words.txt"
with open(file_name, "w", encoding="utf-8") as file:
file.write("code python file student")
with open(file_name, "r", encoding="utf-8") as file:
text = file.read()
words = text.split()
longest = words[0]
for word in words:
if len(word) > len(longest):
longest = word
print(longest)
Write a shopping list.
#There is a shopping list: ["bread", "milk", "cheese"]. Write each item from the list to the file shopping.txt on a new line. Then read the file and print its contents.
products = ["bread", "milk", "cheese"] file_name = "shopping.txt"
Solution
products = ["bread", "milk", "cheese"]
file_name = "shopping.txt"
with open(file_name, "w", encoding="utf-8") as file:
for product in products:
file.write(product + "\n")
with open(file_name, "r", encoding="utf-8") as file:
text = file.read()
print(text)
Sum of numbers from a file.
#Create a file numbers.txt where numbers are written separated by spaces: 5 10 15 20. Read the file, calculate the sum of the numbers, and print the result.
file_name = "numbers.txt"
Solution
file_name = "numbers.txt"
with open(file_name, "w", encoding="utf-8") as file:
file.write("5 10 15 20")
with open(file_name, "r", encoding="utf-8") as file:
text = file.read()
numbers = text.split()
total = 0
for number in numbers:
total += int(number)
print("Sum:", total)
Filter lines by symbol.
#Create a file emails.txt with several lines, some of which contain the @ symbol. Read the file and write only the lines with @ to a new file valid_emails.txt. Then print the contents of the new file.
file_name = "emails.txt" result_file = "valid_emails.txt"
Solution
file_name = "emails.txt"
result_file = "valid_emails.txt"
with open(file_name, "w", encoding="utf-8") as file:
file.write("[email protected]\nhello\[email protected]\ntest")
with open(file_name, "r", encoding="utf-8") as file:
lines = file.readlines()
with open(result_file, "w", encoding="utf-8") as file:
for line in lines:
if "@" in line:
file.write(line)
with open(result_file, "r", encoding="utf-8") as file:
text = file.read()
print(text)
Rewrite a file in uppercase.
#Create a file text.txt with the string "hello file". Read the contents, convert them to uppercase, and overwrite the same file with the new text. Then print the final contents.
file_name = "text.txt"
Solution
file_name = "text.txt"
with open(file_name, "w", encoding="utf-8") as file:
file.write("hello file")
with open(file_name, "r", encoding="utf-8") as file:
text = file.read()
text = text.upper()
with open(file_name, "w", encoding="utf-8") as file:
file.write(text)
with open(file_name, "r", encoding="utf-8") as file:
result = file.read()
print(result)
Report with word count.
#Create a file article.txt with several words. Read the file, count the number of words, and write a line like "Word count: N" to the file report.txt. Then print the contents of report.txt.
article_file = "article.txt" report_file = "report.txt"
Solution
article_file = "article.txt"
report_file = "report.txt"
with open(article_file, "w", encoding="utf-8") as file:
file.write("Python helps practice file reading and writing")
with open(article_file, "r", encoding="utf-8") as file:
text = file.read()
words = text.split()
count = len(words)
with open(report_file, "w", encoding="utf-8") as file:
file.write(f"Word count: {count}")
with open(report_file, "r", encoding="utf-8") as file:
result = file.read()
print(result)