【问题标题】:Open file in universal-newline mode when using pkg_resources?使用 pkg_resources 时以通用换行模式打开文件?
【发布时间】:2010-10-29 13:51:45
【问题描述】:

我正在处理一个 CSV 文件并具有以下工作代码:

reader = csv.reader(open(filename, 'rU'), dialect='excel')
header = reader.next()

但是,为了与代码库中的其他地方兼容,我需要使用使用pkg_resources.resource_stream 的文件对象,如下所示:

fileobj = pkg_resources.resource_stream('foo', 'tests/bar.csv')
reader = csv.reader(fileobj, dialect='excel')
header = reader.next()

(我在这里简化了 - 基本上 csv.reader 代码位于我无法控制的函数中,它需要 fileobj。)

这会引发以下错误。

Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

知道如何在fileobj 中使用通用换行模式吗?我在pkg_resources 文档中看不到任何关于此的内容。

谢谢。

【问题讨论】:

    标签: python csv pkg-resources


    【解决方案1】:

    如果流总是有 fd(例如因为它是文件系统上正常打开的文件),您可以使用 os.fdopen(fileobj.fileno(), 'rU') 以正确的模式打开它。

    【讨论】:

      猜你喜欢
      • 2011-10-07
      • 2012-03-17
      • 2013-12-01
      • 2023-03-06
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2016-07-01
      • 2018-07-27
      相关资源
      最近更新 更多