【问题标题】:Open the file in universal-newline mode using the CSV Django module使用 CSV Django 模块以通用换行模式打开文件
【发布时间】:2011-10-07 07:17:48
【问题描述】:

我正在尝试访问 Django 中的 model.filefield 以使用 csv 模块解析 Python 中的 CSV 文件。它在 Windows 上运行,但在 Mac 上它给了我这个:

Exception Type: Error

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

这是代码:

myfile = customerbulk.objects.all()[0].fileup

mydata = csv.reader(myfile)
    for email,mobile,name,civilid in mydata:
        print email,mobile,name,civilid

【问题讨论】:

  • 这是什么customerbulk.objects.all()[0].fileup 东西。它是模型上的文件名吗?
  • fileup = models.FileField(verbose_name="CsvFile",upload_to='ExcelFiles') 如果我进行像 customerbulk.objects.get(pk=1) 这样的小查询
  • 使用rU的确切原因(与open()函数有关,不是csv特有的。):In addition to the standard fopen() values mode may be 'U' or 'rU'. Python is usually built with universal newlines support; supplying 'U' opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention '\n', the Macintosh convention '\r', or the Windows convention '\r\n'.docs.python.org/2/library/functions.html#open
  • 在 Python >= 3 中,使用 newline='' 而不是 mode='U'

标签: django macos csv newline python-2.x


【解决方案1】:

我终于找到了解决办法:

mypath = customerbulk.objects.get(pk=1).fileup.path
o = open(mypath,'rU')
mydata = csv.reader(o)

【讨论】:

  • 我相信你可以简化这个。刚打开文件就开始寻找似乎很奇怪。以下帮助我克服了使用默认值从 Excel 电子表格导出到 CSV 的相同问题:data = csv.reader(open(FILENAME, 'rU'), quotechar='"', delimiter = ',')
  • 是的,打开后不需要寻找文件的开头。 >>>o = open(mypath, 'rU') 位,带有 'rU' 标志是在我的案例中起作用的重要魔法。
  • PEP278 解释了rU 的含义:In a Python with universal newline support open() the mode parameter can also be "U", meaning "open for input as a text file with universal newline interpretation". Mode "rU" is also allowed, for symmetry with "rb".
  • @Xiao +1 链接到解释基本原理的原始 PEP。
  • 在 Python >= 3 中,请改用newline,默认为newline=None,类似于newline='',除了它还将换行符转换为\n。我不确定其中哪一个相当于mode='U'
猜你喜欢
  • 2013-12-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 2023-03-06
  • 1970-01-01
  • 2012-03-17
  • 1970-01-01
  • 2019-10-31
相关资源
最近更新 更多