使用 Python 的内置 .csv 模块进行编写

2024-04-23

[请注意,这是一个与已经回答的问题不同的问题如何使用 Python 的内置 .csv writer 模块替换列? https://stackoverflow.com/questions/1019200/how-to-replace-a-column-using-pythons-built-in-csv-writer-module]

我需要在一个巨大的 Excel .csv 文件中进行查找和替换(特定于一列 URL)。由于我正处于尝试自学脚本语言的开始阶段,我想我会尝试在 python 中实现该解决方案。

当我在更改条目内容后尝试写回 .csv 文件时遇到问题。我读过官方 csv 模块文档 http://docs.python.org/3.0/library/csv.html关于如何使用 writer,但没有涵盖这种情况的示例。具体来说,我试图在一个循环中完成读取、替换和写入操作。但是,不能在 for 循环的参数和 writer.writerow() 的参数中使用相同的“行”引用。那么,一旦我在 for 循环中进行了更改,我应该如何写回文件?

edit:我执行了S. Lott和Jimmy的建议,结果还是一样

edit #2:根据 S. Lott 的建议,我将“rb”和“wb”添加到 open() 函数中

import csv

#filename = 'C:/Documents and Settings/username/My Documents/PALTemplateData.xls'

csvfile = open("PALTemplateData.csv","rb")
csvout = open("PALTemplateDataOUT.csv","wb")
reader = csv.reader(csvfile)
writer = csv.writer(csvout)

changed = 0;

for row in reader:
    row[-1] = row[-1].replace('/?', '?')
    writer.writerow(row)                  #this is the line that's causing issues
    changed=changed+1

print('Total URLs changed:', changed)

edit:供您参考,这是new来自解释器的完整回溯:

Traceback (most recent call last):
  File "C:\Documents and Settings\g41092\My Documents\palScript.py", line 13, in <module>
    for row in reader:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

您无法读取和写入同一个文件。

source = open("PALTemplateData.csv","rb")
reader = csv.reader(source , dialect)

target = open("AnotherFile.csv","wb")
writer = csv.writer(target , dialect)

所有文件操作的正常方法是创建原始文件的修改副本。不要尝试就地更新文件。这只是一个糟糕的计划。


Edit

在行中

source = open("PALTemplateData.csv","rb")

target = open("AnotherFile.csv","wb")

“rb”和“wb”是绝对必需的。每次您忽略这些内容时,您都会以错误的格式打开文件进行阅读。

您必须使用“rb”来读取 .CSV 文件。 Python 2.x 没有选择。在 Python 3.x 中,您可以省略这一点,但显式使用“r”以使其清晰。

您必须使用“wb”来写入 .CSV 文件。 Python 2.x 没有选择。对于 Python 3.x,您必须使用“w”。


Edit

看来您正在使用Python3。您需要从“rb”和“wb”中删除“b”。

读这个:http://docs.python.org/3.0/library/functions.html#open http://docs.python.org/3.0/library/functions.html#open

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Python 的内置 .csv 模块进行编写 的相关文章

随机推荐