"""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 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPython 3.12, real UTF-8 fixture and output files, text newline policy and dialect lifecycle
入口文件:projects/python-lab/python-csv.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python-csv.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPython 3.12, real UTF-8 fixture and output files, text newline policy and dialect lifecycle。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a293.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip