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

ign*_*lut 7 python csv file-io python-3.x

[请注意,这是一个与已经回答的问题不同的问题如何使用Python的内置.csv编写器模块替换列?]

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

当我在更改条目内容后尝试写回.csv文件时,我遇到了麻烦.我已经阅读了有关如何使用编写器官方csv模块文档,但是没有一个示例涵盖了这种情况.具体来说,我试图在一个循环中完成读取,替换和写入操作.但是,在for循环的参数和writer.writerow()的参数中都不能使用相同的'row'引用.所以,一旦我在for循环中进行了更改,我应该如何写回文件?

编辑:我实施了S. Lott和Jimmy的建议,结果仍然相同

编辑#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)
Run Code Online (Sandbox Code Playgroud)

编辑:供您参考,这是解释器的完整回溯:

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?)
Run Code Online (Sandbox Code Playgroud)

S.L*_*ott 10

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

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

target = open("AnotherFile.csv","wb")
writer = csv.writer(target , dialect)
Run Code Online (Sandbox Code Playgroud)

ALL文件操作的常规方法是创建原始文件的修改后的COPY.不要尝试更新文件.这只是一个糟糕的计划.


编辑

在线

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

target = open("AnotherFile.csv","wb")
Run Code Online (Sandbox Code Playgroud)

绝对需要"rb"和"wb".每次忽略这些时,都会打开文件以便以错误的格式读取.

您必须使用"rb"来读取.CSV文件.Python 2.x别无选择.使用Python 3.x,您可以省略它,但明确使用"r"来表明它.

您必须使用"wb"来编写.CSV文件.Python 2.x别无选择.使用Python 3.x,您必须使用"w".


编辑

看来你正在使用Python3.你需要从"rb"和"wb"中删除"b".

阅读本文:http://docs.python.org/3.0/library/functions.html#open

  • ""rb"和"wb"是绝对必需的.":不在Python 3.那里,你应该用newline =''调用open(). (2认同)