首页 > 解决方案 > 防止在读取/写入 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 数据(即不隐式更改任何内容)?

标签: pythonmacoscsv

解决方案


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)

推荐阅读