Python3 File

文件打开模式、读写方法、指针定位与常用文件对象方法速查。

Beginner
Key Pointsopen 必须配 with;文本模式指定 encoding;w 会清空文件、a 追加、r+ 可读写。

打开文件

open(file, mode, encoding) returns a file object. Modes: r read (default), w truncate-write, a append, x exclusive create, b binary, + read-write. w empties the file immediately.

ModeMeaning
rRead only, file must exist
wWrite, truncates or creates
aAppend, creates if missing
xCreate, fails if exists
bBinary mode, combine as rb/wb
+Read and write, combine as r+
Python
with open('demo.txt', 'w', encoding='utf-8') as f:
    f.write("first\n")

with open('demo.txt', 'a', encoding='utf-8') as f:
    f.write("second\n")

with open('demo.txt', 'r', encoding='utf-8') as f:
    print(repr(f.read()))

try:
    open('nope.txt', 'r', encoding='utf-8')
except FileNotFoundError as e:
    print("FileNotFoundError:", e.strerror)
Output
'first\nsecond\n'
FileNotFoundError: No such file or directory

读文件

read() loads everything, read(n) reads n characters, readline() one line, readlines() a list of lines. For big files iterate line by line instead of loading it all.

Python
with open('demo.txt', 'w', encoding='utf-8') as f:
    f.write("a1\nb2\nc3\n")

with open('demo.txt', encoding='utf-8') as f:
    print(f.readline().strip())
    print(f.read(2))

with open('demo.txt', encoding='utf-8') as f:
    print(len(f.readlines()))

with open('demo.txt', encoding='utf-8') as f:
    print([line.strip() for line in f])
Output
a1
b2
3
['a1', 'b2', 'c3']

写文件

write(str) writes a string and returns the character count; writelines(list) writes a sequence of strings without adding newlines. Writing non-strings raises TypeError.

Python
with open('out.txt', 'w', encoding='utf-8') as f:
    n = f.write("hello")
    f.writelines(["\n", "world", "\n"])

print("chars:", n)

with open('out.txt', encoding='utf-8') as f:
    print(repr(f.read()))

try:
    with open('bad.txt', 'w', encoding='utf-8') as f:
        f.write(123)
except TypeError as e:
    print("TypeError:", e)
Output
chars: 5
'hello\nworld\n'
TypeError: write() argument must be str, not int

文件指针与常用方法

tell() reports the position, seek(offset, whence) moves it (0 start, 1 current, 2 end), truncate(n) cuts the file, flush() pushes buffers out, and closed reports the state.

Python
with open('p.txt', 'w', encoding='utf-8', newline='') as f:
    f.write("0123456789")

with open('p.txt', 'r+', encoding='utf-8', newline='') as f:
    print(f.read(3), f.tell())
    f.seek(0)
    print(f.read(2))
    f.seek(0, 2)
    print(f.tell())

with open('p.txt', encoding='utf-8') as f:
    print(f.closed)
print(f.closed)
Output
012 3
01
10
False
True

Friends & Partners