使用CSV Django模块以通用换行模式打开文件


86

我正在尝试访问model.filefieldDjango中的,以使用该模块解析Python中的CSV文件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东西 它是模型上的文件名吗?
SingleNegationElimination

fileup = models.FileField(verbose_name = “CsvFile”,upload_to = 'ExcelFiles')如果我喜欢customerbulk.objects.get一个小的查询(PK = 1)
莫哈末

1
使用的确切原因rU(与open()函数有关,而与csvIn 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'. 无关
zengr 2013年

在Python> = 3中,使用newline=''代替mode='U'
tricasse

Answers:


150

我终于找到了解决方案:

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

2
我相信您可以简化此过程。刚打开文件后,尝试重新开始似乎很奇怪。以下内容帮助我克服了使用默认设置将Excel电子表格导出为CSV时遇到的相同问题:data = csv.reader(open(FILENAME,'rU'),quotechar ='“',delimiter =',')
timbo,

4
是的,没有必要在打开文件后立即开始查找文件。>>> o = open(mypath,'rU')位,带有'rU'标志是在我的案例中起作用的重要魔术。
2013年

13
PEP278解释了什么意思rUIn 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

@Xiao +1,用于链接到原始PEP,以解释其基本原理。
Naymesh Mistry

在Python> = 3中,newline改用,默认值newline=None与相似,newline=''除了它还将换行符转换为\n。我不确定其中哪一个等同于mode='U'
timdiels
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.