Python csv:读写记录、表头与方言
用一份含中文、逗号、引号和字段内换行的盘点表,核对文件读写与 TSV 设置。
学完这一章,你能够
- 用一份含中文、逗号、引号和字段内换行的盘点表,核对文件读写与 TSV 设置。
读取文本流中的逻辑记录
CSV 用文本交换表格数据。字段可含分隔符或换行,需要按双方约定的引用规则解析。一个逻辑记录可能跨多行,不能用逐行 split(',') 解析这类数据。
用 open(path, 'r', encoding='utf-8', newline='') 打开本实验的 UTF-8 文件,把文本流交给 csv.reader。next(reader) 读一条逻辑记录,for 循环可继续读取。普通模式下各字段是字符串,数字列需要根据数据规则显式转换。
newline='' 让 csv 处理换行。实验的一个字段含 CRLF,保留原样时可往返一致。读取时若使用默认换行转换,字段里的 CRLF 会变为 LF。with 退出后会关闭流。
写入单条记录或一组记录
以 'w' 打开输出文件会截断原有内容,因此实验只在临时目录写入。设置 encoding='utf-8' 和 newline='',writer 负责分隔符、引号与行结束符。Windows 的默认文本换行转换叠加在 CSV 的 CRLF 上可能产生多余的回车。
writerow 接受一个字段序列,writerows 消费多条记录。默认设置会引用包含分隔符、双引号或行结束字符的字段。数值写成文本,None 默认写成空字段,读回时无法凭这一列分辨 None 与空字符串。
实验先写表头,再用生成器写多条记录,逐字节核对 UTF-8、CRLF 和双写引号,并用 reader 重新读出含换行的备注。
按字段名读写表头
DictReader 未给 fieldnames 时读取第一条逻辑记录作为表头,后续每行返回字典。显式传 fieldnames 时首行也作为数据读入。短行的缺项用 restval 补足,超出表头的字段作为列表放在 restkey 对应的位置。
DictWriter 要求传入 fieldnames,字段顺序按这个列表。writeheader 显式写出表头,再写字典记录。缺键默认写空字段,可以设置 restval。多余键默认抛出 ValueError,明确指定 extrasaction="ignore" 后才忽略。
实验用两个字段导出盘点记录,再用 DictReader 按字段名读取。数量仍是字符串,示例随后用 int 转换并核对总数。
配置分隔符、引用字符和方言
默认 excel 方言以逗号分隔、使用双引号并按最少引用规则写入。delimiter 与 quotechar 都可指定单字符,quoting 决定引用规则。QUOTE_ALL 写入时引用每个字段,QUOTE_NONE 则不引用,字段中含制表符等特殊字符时需要设置 escapechar。
skipinitialspace=True 只跳过分隔符紧随的空格,字段末尾和引号内的空格仍保留。lineterminator 控制 writer 的记录结束符,reader 按 CR 或 LF 识别记录结束,不用这个选项指定任意记录边界。
可把一组格式设置注册成方言,再按名称选择。register_dialect、list_dialects、unregister_dialect 管理的是进程内注册表。实验为无引号 TSV 注册单独名称,读取字面引号与中文字段,最后取消注册。项目对外交换时应明确双方选用的方言和编码。
下载 UTF-8 样本并复跑
解压后运行 python python-csv.py。压缩包里的 CSV 和 TSV 是本站自编输入,实验会在临时目录生成另一份 CSV。可修改样本中的分隔符或字段内容,再观察哪些预期随之变化。
所需环境:CPython 3.12 标准库
ZIP SHA256:8d124dec7e28a81a4112c8f32925ab16c48fee26715fbceca46accdb8aed3055
模块入口
| 参数或方法 | 作用和条件 |
|---|---|
| csv.reader(csvfile, dialect="excel", **fmtparams) | 从文本迭代器解析记录,默认每条返回字符串列表。 |
| csv.writer(csvfile, dialect="excel", **fmtparams) | 从字段序列生成文本记录,按方言写入文本流。 |
| csv.DictReader(csvfile, fieldnames=None, …) | 按表头或显式字段名把后续记录映射为字典。 |
| csv.DictWriter(csvfile, fieldnames, …) | 按必填的字段名顺序写入字典值,表头需显式写。 |
| csv.register_dialect(name, dialect="excel", **fmtparams) | 在进程内为一组格式选项登记名称。 |
| csv.unregister_dialect(name) | 从注册表移除名称,名称不存在时抛出 csv.Error。 |
| csv.list_dialects() | 返回当前登记的方言名称列表。 |
记录读写方法
| 参数或方法 | 作用和条件 |
|---|---|
| next(reader) / reader.__next__() | 获取下一条逻辑记录。读尽后触发 StopIteration。 |
| writer.writerow(row) | 按配置写入一条记录。 |
| writer.writerows(rows) | 迭代输入并逐条写入。 |
字典表头
| 参数或方法 | 作用和条件 |
|---|---|
| DictReader.fieldnames / DictWriter.fieldnames | 读取器可从首条记录推断,写入器使用指定顺序。 |
| DictWriter.writeheader() | 按 fieldnames 的顺序写出一条表头记录。 |
方言和格式参数
| 参数或方法 | 作用和条件 |
|---|---|
| delimiter | 单字符字段分隔符,默认 excel 方言为逗号。可改为 \t 等。 |
| quotechar | 标记引用字段的单字符,默认 excel 方言为双引号。 |
| quoting | 控制读写如何解释或添加引号,具体行为取决于选定常量。 |
| skipinitialspace | 设为 True 后跳过分隔符后的空格。 |
| lineterminator | writer 写出的记录分隔字符串,默认 \r\n。reader 不用该值自定义边界。 |
| dialect | reader、writer 及字典版本可接受已注册的名称或 Dialect 参数;单独参数可覆盖设置。 |
本章自编源码与运行范围
"""Replay CSV and TSV operations with owned UTF-8 files and temporary output."""
import csv
from io import StringIO
import json
from pathlib import Path
from tempfile import TemporaryDirectory
def main():
checks = []
def check(name, actual, expected, inputs, operation):
if actual != expected:
raise AssertionError((name, actual, expected))
checks.append(dict(name=name, inputs=inputs, operation=operation, actual=actual,
expected=expected, passed=True))
def rejects(name, error, operation, inputs):
try:
operation()
except error as raised:
check(name, type(raised).__name__, error.__name__, inputs, 'Run the operation and record its exception')
else:
raise AssertionError(name)
fixtures = Path(__file__).resolve().parent / 'csv-lab'
csv_input = fixtures / 'stock.csv'
tsv_input = fixtures / 'departures.tsv'
expected_rows = [
['物件', '数量', '备注'],
['棉线', '8', '小盒,蓝色'],
['玻璃', '3', '标记"轻放"\r\n置于二层'],
]
with csv_input.open('r', encoding='utf-8', newline='') as stream:
reader = csv.reader(stream)
header = next(reader)
body = [row for row in reader]
exhausted = next(reader, None)
lines_read = reader.line_num
check('reader iteration and UTF-8 fields', [header, body, exhausted, lines_read, stream.closed],
[expected_rows[0], expected_rows[1:], None, 4, True], 'stock.csv, UTF-8 with 4 physical lines',
'Read one record using next and the rest using iteration, then inspect exhaustion and closure')
with csv_input.open('r', encoding='utf-8') as stream:
normalized = list(csv.reader(stream))[-1][-1]
check('newline translation changes quoted CRLF', [body[-1][-1], normalized],
['标记"轻放"\r\n置于二层', '标记"轻放"\n置于二层'], 'stock.csv with a quoted field containing CRLF',
'Compare a preserved field with text-mode universal newline translation')
with TemporaryDirectory(prefix='mbsky-csv-') as temp:
root = Path(temp)
output = root / 'stock-export.csv'
output.write_bytes(b'obsolete data that is discarded')
with output.open('w', encoding='utf-8', newline='') as stream:
writer = csv.writer(stream)
writer.writerow(header)
writer.writerows(row for row in body)
written = output.read_bytes()
with output.open('r', encoding='utf-8', newline='') as stream:
recovered = list(csv.reader(stream))
expected_bytes = ('物件,数量,备注\r\n棉线,8,"小盒,蓝色"\r\n'
'玻璃,3,"标记""轻放""\r\n置于二层"\r\n').encode('utf-8')
check('writer byte-level round trip', [written.hex(), recovered], [expected_bytes.hex(), expected_rows],
expected_rows, 'Truncate old bytes, write one header and generated records, read bytes and parse them')
translated = root / 'translated.csv'
with translated.open('w', encoding='utf-8', newline='\r\n') as stream:
csv.writer(stream).writerow(['slot', 9])
check('forced CRLF translation duplicates carriage return',
translated.read_bytes().decode('utf-8'), 'slot,9\r\r\n', 'CSV CRLF plus text newline set to CRLF',
'Write one record with explicit Windows-style translation and inspect literal bytes')
dict_output = root / 'counts.csv'
with dict_output.open('w', encoding='utf-8', newline='') as stream:
writer = csv.DictWriter(stream, ['物件', '数量'])
writer.writeheader()
writer.writerow({'数量': 8, '物件': '棉线'})
writer.writerows([{'数量': 3, '物件': '玻璃'}])
with dict_output.open('r', encoding='utf-8', newline='') as stream:
restored = list(csv.DictReader(stream))
check('DictWriter header order and round trip',
[dict_output.read_bytes().decode('utf-8'), restored, sum(int(row['数量']) for row in restored)],
['物件,数量\r\n棉线,8\r\n玻璃,3\r\n', [{'物件': '棉线', '数量': '8'}, {'物件': '玻璃', '数量': '3'}], 11],
'Two dictionaries with key order differing from fieldnames',
'Write a header, read back by field names, convert counts and sum')
with csv_input.open('r', encoding='utf-8', newline='') as stream:
named = csv.DictReader(stream)
check('DictReader inferred header and named data',
[named.fieldnames, [(row['物件'], row['数量']) for row in named]],
[header, [('棉线', '8'), ('玻璃', '3')]], 'stock.csv with header and two records',
'Infer header and retrieve named fields in the data')
check('DictReader explicit names keep the first record',
list(csv.DictReader(['x,2', 'y,3'], fieldnames=['item', 'count'])),
[{'item': 'x', 'count': '2'}, {'item': 'y', 'count': '3'}], ['x,2', 'y,3'],
'Supply names without consuming the first record as a header')
check('DictReader irregular rows retain extras and fill missing',
list(csv.DictReader(['item,qty', 'paper', 'wood,2,tag'], restval='?', restkey='extra')),
[{'item': 'paper', 'qty': '?'}, {'item': 'wood', 'qty': '2', 'extra': ['tag']}],
['item,qty', 'paper', 'wood,2,tag'], 'Parse short and long records with explicit policies')
stream = StringIO(newline='')
plain = csv.DictWriter(stream, ['item', 'qty'], restval='?')
rejects('DictWriter rejects unknown keys by default', ValueError,
lambda: plain.writerow({'item': 'paper', 'color': 'blue'}), 'unknown key color')
csv.DictWriter(stream, ['item', 'qty'], restval='?', extrasaction='ignore').writerow(
{'item': 'paper', 'color': 'blue'})
check('DictWriter can drop extras and fill missing keys', stream.getvalue(), 'paper,?\r\n',
{'item': 'paper', 'color': 'blue'}, 'Select ignore and replace missing qty with restval')
stream = StringIO(newline='')
csv.writer(stream).writerow([None, '', 8])
check('None and empty string share a serialized field',
list(csv.reader(StringIO(stream.getvalue(), newline=''))), [['', '', '8']], [None, '', 8],
'Serialize and parse back the ambiguous empty values')
check('delimiter override', list(csv.reader(['box;7'], delimiter=';')), [['box', '7']], 'box;7',
'Override the default field separator')
stream = StringIO(newline='')
csv.writer(stream, quotechar="'").writerow(['batch', 'red,large'])
check('custom quotechar', [stream.getvalue(), list(csv.reader(StringIO(stream.getvalue()), quotechar="'"))],
["batch,'red,large'\r\n", [['batch', 'red,large']]], ['batch', 'red,large'],
'Write and read a comma-bearing field surrounded with single quotes')
quoted = StringIO(newline='')
csv.writer(quoted, quoting=csv.QUOTE_ALL).writerow(['rack', 7])
bare = StringIO(newline='')
csv.writer(bare, quoting=csv.QUOTE_NONE, escapechar='\\').writerow(['rack,east', '7'])
read_bare = list(csv.reader(StringIO(bare.getvalue()), quoting=csv.QUOTE_NONE, escapechar='\\'))
check('quote all, quote none and escaping', [quoted.getvalue(), bare.getvalue(), read_bare],
['"rack","7"\r\n', 'rack\\,east,7\r\n', [['rack,east', '7']]], ['rack,east', '7'],
'Compare all-quoted output with escaping instead of quoting')
rejects('quote none without an escape fails', csv.Error,
lambda: csv.writer(StringIO(), quoting=csv.QUOTE_NONE).writerow(['rack,east', '7']),
'field contains delimiter and writer has no escapechar')
padded = 'oak, pine ," fir "'
check('skipinitialspace preserves other spaces',
[next(csv.reader([padded])), next(csv.reader([padded], skipinitialspace=True))],
[['oak', ' pine ', ' fir '], ['oak', 'pine ', ' fir ']], padded,
'Compare parsing with and without skipinitialspace')
stream = StringIO(newline='')
csv.writer(stream, lineterminator='!').writerows([['x', 'y'], ['z', 'w']])
custom = stream.getvalue()
check('writer lineterminator is not reader boundary',
[custom, list(csv.reader(StringIO(custom), lineterminator='!'))],
['x,y!z,w!', [['x', 'y!z', 'w!']]], ['x,y', 'z,w'],
'Write a custom terminator and observe that reader does not split on it')
alias = 'mbsky_departure_tsv'
before = csv.list_dialects()
csv.register_dialect(alias, delimiter='\t', quoting=csv.QUOTE_NONE, lineterminator='\n')
try:
with tsv_input.open('r', encoding='utf-8', newline='') as stream:
timetable = list(csv.reader(stream, dialect=alias))
with tsv_input.open('r', encoding='utf-8', newline='') as stream:
named_timetable = list(csv.DictReader(stream, dialect=alias))
writer_output = StringIO(newline='')
csv.writer(writer_output, dialect=alias, delimiter='|').writerow(['A', 'B'])
check('registered TSV dialect and literal quotes',
[timetable, named_timetable[0], writer_output.getvalue()],
[[['站台', '目的地'], ['B2', '"东站"'], ['C4', '河口']],
{'站台': 'B2', '目的地': '"东站"'}, 'A|B\n'],
'departures.tsv with tabs and literal double quotes',
'Use the registered name for both readers, then override the separator on the writer')
during = csv.list_dialects()
check('list dialects before and after registration',
[alias in before, alias in during, 'excel' in before], [False, True, True], alias,
'Compare registration membership and the built-in excel dialect')
finally:
csv.unregister_dialect(alias)
check('unregister removes dialect', alias in csv.list_dialects(), False, alias,
'Read the registered names after removal')
rejects('unknown dialect raises csv Error', csv.Error, lambda: csv.get_dialect(alias), alias)
print(json.dumps(checks, ensure_ascii=False))
if __name__ == '__main__':
main()
所需环境:Windows CPython 3.12, real UTF-8 fixture and output files, text newline policy and dialect lifecycle
当前源码 SHA256:6a6f45e8b6ea9624d663580113bff83d6e10db16165c762cb23a7ad74fe457f2
当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。
常见错误与边界
- 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。
练习与解答
使用本站实例修改一个条件,先写下预期,再实际运行。
展开参考解答
比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。