0Pricing
Python Academy · Lesson

Reading and Writing Files

Use read_text and write_text.

Reading and Writing Files is a free Python Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

File I/O the pathlib Way

pathlib paths can read and write files directly, without an explicit open() for simple cases. The methods read_text, write_text, read_bytes, and write_bytes cover the common needs.

write_text

write_text() writes a string to the file, creating it if needed and replacing any existing contents. It returns the number of characters written.

from pathlib import Path

p = Path('greeting.txt')
n = p.write_text('Hello, pathlib!')
print('wrote', n, 'characters')

read_text

read_text() opens the file, reads all of it, and closes it, returning the whole content as a string.

from pathlib import Path

p = Path('greeting.txt')
p.write_text('Hello, pathlib!')
content = p.read_text()
print(content)

No Manual Close Needed

These helpers open and close the file for you, so you avoid the boilerplate of a with open(...) block for one-shot reads and writes.

from pathlib import Path

p = Path('notes.txt')
p.write_text('line one')
print(p.read_text())

Specifying Encoding

Pass an encoding argument to control text encoding. UTF-8 is a safe, explicit choice for portability.

from pathlib import Path

p = Path('uni.txt')
p.write_text('cafe resume', encoding='utf-8')
print(p.read_text(encoding='utf-8'))

Working with Bytes

For binary data use write_bytes() and read_bytes(), which deal in bytes objects instead of strings.

from pathlib import Path

p = Path('data.bin')
p.write_bytes(b'\x00\x01\x02')
print(p.read_bytes())

Appending and Advanced Modes

The one-shot helpers always overwrite. For appending or streaming, call open() on the Path to get a normal file object usable in a with block.

from pathlib import Path

p = Path('log.txt')
p.write_text('start\n')
with p.open('a') as f:
    f.write('more\n')
print(p.read_text())

Reading Line by Line

Read all text, then split into lines, or open the path and iterate. Splitting the result of read_text() is simplest for small files.

from pathlib import Path

p = Path('multi.txt')
p.write_text('a\nb\nc\n')
for line in p.read_text().splitlines():
    print('line:', line)

Creating Parent Directories

Writing fails if the parent directory does not exist. Use mkdir(parents=True, exist_ok=True) on the parent first to create the folder tree.

from pathlib import Path

p = Path('out/sub/file.txt')
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text('done')
print(p.read_text())

Deleting Files

Remove a file with unlink(). Passing missing_ok=True avoids an error if the file is already gone.

from pathlib import Path

p = Path('temp.txt')
p.write_text('bye')
print(p.exists())
p.unlink(missing_ok=True)
print(p.exists())

Read, Transform, Write

A common pattern is to read a file, transform its text, and write it back. pathlib makes this a tidy three-line operation.

from pathlib import Path

p = Path('caps.txt')
p.write_text('hello world')
p.write_text(p.read_text().upper())
print(p.read_text())

Quick Check

What does Path('a.txt').write_text('hi') do if the file already exists?

Recap

You learned to read and write files with pathlib.

  • write_text/read_text handle whole-file string I/O.
  • write_bytes/read_bytes handle binary data.
  • Use open() for appending or streaming.
  • Create parents with mkdir and remove with unlink.

Frequently asked questions

Is the “Reading and Writing Files” lesson free?

Yes — the full text of “Reading and Writing Files” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Reading and Writing Files”?

Use read_text and write_text. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Reading and Writing Files” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The Path Object
  2. Reading and Writing Files
  3. Globbing and Iterating
  4. Path Manipulation
← Back to Python Academy