iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

File Methods

File-object reference. Returned by open(); most useful inside a with block so it closes deterministically.

Read

MethodReturns
read(size=-1)Up to size characters / bytes; whole file if -1.
readline(size=-1)One line (or partial).
readlines()All lines as a list (newlines kept).
iterating for line in f:Streams one line at a time.

Write

MethodWhat it does
write(s)Write a string (or bytes in binary mode).
writelines(iter)Write each item; does not add newlines.
flush()Push buffered output to disk.

Position

MethodWhat it does
tell()Current position (bytes in binary, opaque in text).
seek(offset, whence=0)Move to a position. whence: 0 = start, 1 = current, 2 = end.

Lifecycle

MethodWhat it does
close()Close. Done automatically by with.
closedBool — is it closed?
readable() / writable() / seekable()Capability tests.

The pathlib alternative

For one-shot reads/writes, Path.read_text / write_text is shorter:

PYTHON
from pathlib import Path
text = Path('hello.txt').read_text(encoding='utf-8')
Path('out.txt').write_text('hi', encoding='utf-8')
Tip: Pass encoding='utf-8' for text files. The platform default still trips people up on Windows.

Example

Example
# file = open('hello.txt')
# file.read(), file.readline(), file.readlines()
# file.write('x'), file.writelines(['a\n','b\n'])
# file.seek(0), file.tell(), file.close()
print('File methods — see file-handling for runnable demos.')
Try it Yourself »

Exercise

Move to the start of the file.

f. (0)

Test yourself

Q1. Iterating "for line in f:" yields…
Q2. Pathlib write a string with…
Q3. Move cursor to start with…

Discussion

Loading…