【问题标题】:Use newline='' with click.open_file() to support OS-indepent new-lines & CSVs使用 newline=\'\' 和 click.open_file() 来支持与操作系统无关的换行符和 CSV
【发布时间】:2022-08-24 16:48:28
【问题描述】:
PyPi click 库有一个 open_file() 函数,它优于 Python 的 open() 函数,因为它可以“智能地打开 stdin/stdout 以及任何其他文件”(例如,当文件名指定为-)。
不幸的是,它似乎不支持 Python 的标准 CSV 模块正确 handle new-lines in an OS-independent manner 所需的 Python 内置 open() 函数的 newline 参数。如果没有这个,在 Windows 上生成的 CSV 在每行之间会有额外的空行。
是否可以使用 click\'s open_file() 以独立于操作系统的方式读取/写入 CSV?
标签:
python
command-line-interface
file-handling
【解决方案1】:
根据 Github 上的问题讨论,click 本身并不支持:
我发现以下解决方法对我有用:
if output_path == '-':
# Specifically use click's open_file only for its stdout stream
file_ctx_manager = click.open_file(output_path, 'w', encoding='utf-8')
else:
# Use open() directly for actual files because the CSV requires newline='' to be OS-independent
file_ctx_manager = open(output_path, 'w', newline='', encoding='utf-8')
with file_ctx_manager as csv_file:
writer = csv.writer(csv_file, quoting=csv.QUOTE_MINIMAL)
writer.writerow([])