File Methods
File-object reference. Returned by open(); most useful inside a with block so it closes deterministically.
Read
| Method | Returns |
|---|---|
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
| Method | What 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
| Method | What 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
| Method | What it does |
|---|---|
close() | Close. Done automatically by with. |
closed | Bool — 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)
Four letters.
Discussion
Loading…