Python3 File
文件打开模式、读写方法、指针定位与常用文件对象方法速查。
打开文件
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.
| Mode | Meaning |
|---|---|
| r | Read only, file must exist |
| w | Write, truncates or creates |
| a | Append, creates if missing |
| x | Create, fails if exists |
| b | Binary mode, combine as rb/wb |
| + | Read and write, combine as r+ |
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)'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.
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])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.
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)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.
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)012 3
01
10
False
True打开文件
open(file, mode, encoding) 返回文件对象。模式有 r 读(默认)、w 覆盖写、a 追加、x 独占创建、b 二进制、+ 读写。w 会立刻把文件清空。
| 模式 | 含义 |
|---|---|
| r | 只读,文件必须存在 |
| w | 写入,清空或新建 |
| a | 追加,不存在则新建 |
| x | 独占创建,已存在则报错 |
| b | 二进制模式,与 rb/wb 组合 |
| + | 读写,如 r+ |
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)'first\nsecond\n'
FileNotFoundError: No such file or directory读文件
read() 一次读完、read(n) 读 n 个字符、readline() 读一行、readlines() 读成列表。大文件应逐行迭代,避免把整个文件塞进内存。
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])a1
b2
3
['a1', 'b2', 'c3']写文件
write(str) 写字符串并返回写入的字符数;writelines(list) 写一组字符串(不会自动加换行)。写入非字符串会抛 TypeError。
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)chars: 5
'hello\nworld\n'
TypeError: write() argument must be str, not int文件指针与常用方法
tell() 返回当前位置,seek(offset, whence) 移动指针(0 开头、1 当前、2 末尾),truncate(n) 截断,flush() 落盘,closed 判断是否已关闭。
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)012 3
01
10
False
True