CSV模块-“用于读卡器中的行”-在Mac和Windows之间

2024-05-21 00:49:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Wing IDE在Mac上开发了一些代码。我开发的代码,利用csv模块,正在工作,并做我想它在我的Mac上。不过,问题是,我写这篇文章的人需要在Windows上使用它。我不关心代码,因为我没有使用任何转义字符。

代码如下所示:

csvfile = open('file.csv', 'r')
csvreader = csv.reader(csvfile, delimiter = ',')
for row in csvreader:
   thisVariable = row[0]  # <<<--------

我在上面输入的“箭头”是在Windows计算机上返回错误的位置。就像我说的,代码在Mac上运行得很好,实际上,这在我编写的代码中是相当低的。还有其他的CSV文件从这个语句读写到上面,它们使用类似的索引。

我真的很感激任何人对这个问题的想法!谢谢!


Tags: 模块csvcsvfile代码利用windowsmacopen
4条回答

我可以看到两个潜在的问题。首先,应该以二进制模式打开文件:

csvfile = open('file.csv', 'rb')

其次,您可能要处理两个不同操作系统的两个不同的行尾。您可以通过在模式后添加U来避免这种情况:

csvfile = open('file.csv', 'rbU')

我还建议通过测试行来保护您的用户不受坏数据的影响。最终结果是:

csvfile = open('file.csv', 'rbU')
csvreader = csv.reader(csvfile, delimiter = ',')
for row in csvreader:
   if not row:
      continue
   thisVariable = row[0]

我可以看到两个潜在的问题。首先,应该以二进制模式打开文件:

csvfile = open('file.csv', 'rb')

其次,您可能要处理两个不同操作系统的两个不同的行尾。您可以通过在模式后添加U来避免这种情况:

csvfile = open('file.csv', 'rbU')

我还建议通过测试行来保护用户不受坏数据的影响。最终结果是:

csvfile = open('file.csv', 'rbU')
csvreader = csv.reader(csvfile, delimiter = ',')
for row in csvreader:
   if not row:
      continue
   thisVariable = row[0]

在Python 2中

您需要将文件作为二进制文件打开:

csvfile = open('file.csv', 'rb')
csvreader = csv.reader(csvfile, delimiter = ',')
for row in csvreader:
    thisVariable = row[0]

http://docs.python.org/2/library/csv.html#csv.reader


在Python 3中

您需要在open语句中设置newline=':

csvfile = open('file.csv', 'r', newline='')
csvreader = csv.reader(csvfile, delimiter = ',')
for row in csvreader:
    thisVariable = row[0]

http://docs.python.org/3.3/library/csv.html#csv.reader

the docscsv.reader应该传递一个以二进制模式打开的文件。
一、 e.:

csvfile = open('file.csv', 'rb')

如果没有看到导致问题的输入文件,我无法确定这是否会解决问题,但很可能会导致其他错误。

相关问题 更多 >