python - CSV 模块 - 'for row in reader' - 在 Mac 和 Windows 之间

标签 python windows macos csv indexing

我在我的 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]

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

关于python - CSV 模块 - 'for row in reader' - 在 Mac 和 Windows 之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15424635/

相关文章:

python - Windows 上 python 的长路径 - os.stat() 相对路径失败?

java - Java 中对 MacOS X 的 native Swing 菜单栏支持

python - 是否可以在 cython 中访问 Polars 的底层数据?

windows - 如何在Windows批处理模式下获取没有文件扩展名的完整路径的文件名

python - Django:仅显示今天的条目时的时区问题

windows - 在 TortoiseGit 中添加命令

python - Homebrew 无法安装 postgresql; python 64位错误

c++ - 无法使用 libvlc 库 (osx) 运行 C++ 程序

python - Django 说 - 没有名为 'blog' 的模块

python - 如何找到一行的值连续达到最大值的次数