我在我的 Mac 上使用 Wing IDE 开发了一些代码。我开发的代码使用了 csv 模块,正在运行,并且可以在我的 Mac 上执行我想要的操作。但是,问题是我为其编写它的人需要在 Windows 上使用它。我不关心代码,因为我没有使用任何转义字符。
代码如下所示:
csvfile = open('file.csv', 'r')
csvreader = csv.reader(csvfile, delimiter = ',')
for row in csvreader:
thisVariable = row[0] # <<<--------
我在上面输入的“箭头”是在 Windows 机器上返回错误的位置。就像我说的那样,代码在 Mac 上运行良好,实际上,这在我编写的代码中还差得很远。这条语句上面还有其他的CSV文件读取和写入,它们使用类似的索引。
如果有人对此问题有任何想法,我将不胜感激!谢谢!
最佳答案
在 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]
关于python - CSV 模块 - 'for row in reader' - 在 Mac 和 Windows 之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15424635/