Python · Syntax · Beginner

Working with files: reading and writing

10 tasks

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.

Opening and reading files

#
A file in Python is opened with open(), which returns a file object. The first argument is the filename, the second is the mode, and encoding should almost always be specified explicitly. ```python file = open("note.txt", "r", encoding="utf-8") content = file.read() file.close() print(content) ``` "r" is read mode — the file must already exist. read() loads the entire file contents as one string. close() releases the file handle. Forgetting to close is a resource leak. The with statement handles closing automatically, even if an exception occurs: ```python with open("note.txt", "r", encoding="utf-8") as file: content = file.read() print(content) ``` After the with block exits, the file is closed. This is the standard pattern — always use with. readlines() gives you a list of lines, each ending with a newline character: ```python with open("tasks.txt", "r", encoding="utf-8") as file: lines = file.readlines() print(len(lines)) # number of lines for line in lines: print(line.strip()) # strip() removes the trailing ``` Iterating directly over the file object also works and is memory-efficient for large files: ```python with open("tasks.txt", "r", encoding="utf-8") as file: for line in file: print(line.strip()) ```

Writing and appending

#
Writing to a file uses mode "w". If the file does not exist, Python creates it. If it already exists, "w" overwrites it completely — the previous content is gone. ```python with open("message.txt", "w", encoding="utf-8") as file: file.write("Hello, file!") ``` write() does not add a newline automatically. To write multiple lines, include \n explicitly or use writelines() with a list of strings that already end with \n: ```python products = ["bread", "milk", "cheese"] with open("shopping.txt", "w", encoding="utf-8") as file: for item in products: file.write(item + "\n") ``` Appending with "a" adds content to the end of the file without erasing what is already there: ```python with open("log.txt", "a", encoding="utf-8") as file: file.write("New entry\n") ``` Use "a" for logs, "w" for files you regenerate each time. The choice matters: using "w" on a log file discards all previous entries. To read a file, modify the content, and write it back: ```python with open("text.txt", "r", encoding="utf-8") as file: content = file.read() with open("text.txt", "w", encoding="utf-8") as file: file.write(content.upper()) ``` Two separate with blocks — one for reading, one for writing. Opening the same file for both "r" and "w" at the same time can cause issues depending on the OS.

File processing patterns

#
Creating a file with initial content and then reading it back — many exercises follow this two-step shape: ```python with open("words.txt", "w", encoding="utf-8") as file: file.write("code python file student") with open("words.txt", "r", encoding="utf-8") as file: content = file.read() words = content.split() longest = max(words, key=len) print(longest) ``` max(iterable, key=function) finds the item for which the function returns the largest value. max(words, key=len) finds the longest word without writing a loop. Filtering lines and writing them to a new file: ```python with open("emails.txt", "r", encoding="utf-8") as file: lines = file.readlines() with open("valid_emails.txt", "w", encoding="utf-8") as file: for line in lines: if "@" in line: file.write(line) ``` Writing a computed report to a separate file: ```python with open("article.txt", "r", encoding="utf-8") as file: content = file.read() word_count = len(content.split()) with open("report.txt", "w", encoding="utf-8") as file: file.write(f"Word count: {word_count}\n") ``` Numbers and other non-string values must be converted to strings before writing. f-strings handle this automatically. Passing an integer directly to write() raises a TypeError.

File operations quick reference

#
**File modes** | Mode | Meaning | If file exists | If file missing | |---|---|---|---| | `'r'` | read | opens normally | `FileNotFoundError` | | `'w'` | write | **overwrites** | creates new | | `'a'` | append | adds to end | creates new | | `'r+'` | read + write | opens normally | `FileNotFoundError` | Always add `encoding='utf-8'` to avoid platform-specific issues. **Standard pattern — always use `with`** ```python with open('file.txt', 'r', encoding='utf-8') as f: content = f.read() # whole file as one string with open('file.txt', 'w', encoding='utf-8') as f: f.write('text\n') # write() does not add newline automatically ``` **Reading methods** | Method | Returns | Use when… | |---|---|---| | `f.read()` | entire file as `str` | small files, full content needed | | `f.readline()` | one line including `\n` | streaming one line at a time | | `f.readlines()` | list of lines with `\n` | need all lines as a list | | `for line in f:` | one line per iteration | large files, memory-efficient | **Writing methods** ```python f.write('text') # write a string (no auto-newline) f.write('line\n') # add \n explicitly f.writelines(['a\n', 'b\n']) # write a list — no auto-newlines added ``` **Common patterns** ```python # Read all lines, strip whitespace with open('f.txt', 'r', encoding='utf-8') as f: lines = [line.strip() for line in f] # Write a list of items, one per line with open('f.txt', 'w', encoding='utf-8') as f: f.write('\n'.join(items)) # Read, transform, write back with open('f.txt', 'r', encoding='utf-8') as f: text = f.read() with open('f.txt', 'w', encoding='utf-8') as f: f.write(text.upper()) # Append a log entry with open('log.txt', 'a', encoding='utf-8') as f: f.write(f'entry\n') ``` **Common pitfalls** ```python f.write(42) # TypeError — must be str, use str(42) open('f.txt', 'w') # 'w' erases existing content immediately # forgetting encoding= causes errors on non-ASCII text ```
01

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)
02

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)
03

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)
04

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)
05

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)
06

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)
07

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)
08

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)
09

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)
10

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)