python - 防止在读取/写入 csv 文件时更改 EOL 字符
问题描述
我正在使用 Python 3.8 中的 csv 模块来读取和修改 macOS 上 .csv 文件中的数据。
Python 似乎更改了我原始 .csv 文件中的所有 EOL 字符。
这种行为是不可取的,因为它使我无法跟踪数据更改。
所有的行都附加了“^M”(即“\r”,也就是回车符)。
结果是,在 Git 中,所有行都标记为已更改。
以二进制模式读取原始 .csv 文件时,Python 告诉我原始 EOL 字符是 '\r\n'。
所以我在写入 .csv 时尝试使用这个 EOL 字符:
def file_to_rows(path):
rows = []
with open(path) as csv_file:
row_reader = csv.reader(
csv_file,
delimiter=';',
quotechar='|',
quoting=csv.QUOTE_MINIMAL)
for row in row_reader:
rows.append(row)
return rows
def rows_to_file(rows, path):
with open(path, 'w', endline='\r\n') as csvfile:
rowswriter = csv.writer(
csvfile,
delimiter=';',
quotechar='|',
quoting=csv.QUOTE_MINIMAL)
for row in rows:
rowswriter.writerow(row)
# Running this function on a file should show NO changes in Git.
def csv_pass_through(path):
rows = file_to_rows(path)
rows_to_file(rows, path)
但git diff
仍然显示一个'^M'已添加到所有行。
因此,Python 似乎添加了太多的回车符。
那么,如何透明地读取/写入 .csv 数据(即不隐式更改任何内容)?
解决方案
martineau 的评论是正确的。您可以在 writer 构造函数中覆盖默认的 '\r\n',如下所示:
def rows_to_file(rows, path):
with open(path, 'w') as csvfile:
rowswriter = csv.writer(
csvfile,
delimiter=';',
lineterminator='\n',
quotechar='|',
quoting=csv.QUOTE_MINIMAL)
for row in rows:
rowswriter.writerow(row)
推荐阅读
- javascript - 显示自定义叠加层的 ag-grid
- c++ - 使用终端 GCC 和 G++ 编译时,仅适用于 Box2D 的未定义参考
- python - 将值打印到 Tkinter 标签
- python - 尝试 Newton-Raphson 时获取“'float' object is not callable”
- python - 如何为 Windows 重写这个多处理代码?
- angular - 如何在过滤属性时将 ViewChildren QueryList 中的特定项目作为 ElementRef 获取?
- r - 在 R 中使用 pagedown 将 HTML 转换为 pdf
- c++ - 使用 C++ 创建一个计算器
- c# - 虽然字符串的最大大小约为 0.75GB,但 Visual Studio 显示 5GB 的使用和运行内存,为什么会有差异?
- c - 使用 Visual Studio Code 运行构建命令