Writing with Python's built-in .csv module

前端 未结 3 1881
遥遥无期
遥遥无期 2021-02-03 14:20

[Please note that this is a different question from the already answered How to replace a column using Python’s built-in .csv writer module?]

I need to do a find and rep

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-03 14:48

    You cannot read and write the same file.

    source = open("PALTemplateData.csv","rb")
    reader = csv.reader(source , dialect)
    
    target = open("AnotherFile.csv","wb")
    writer = csv.writer(target , dialect)
    

    The normal approach to ALL file manipulation is to create a modified COPY of the original file. Don't try to update files in place. It's just a bad plan.


    Edit

    In the lines

    source = open("PALTemplateData.csv","rb")
    
    target = open("AnotherFile.csv","wb")
    

    The "rb" and "wb" are absolutely required. Every time you ignore those, you open the file for reading in the wrong format.

    You must use "rb" to read a .CSV file. There is no choice with Python 2.x. With Python 3.x, you can omit this, but use "r" explicitly to make it clear.

    You must use "wb" to write a .CSV file. There is no choice with Python 2.x. With Python 3.x, you must use "w".


    Edit

    It appears you are using Python3. You'll need to drop the "b" from "rb" and "wb".

    Read this: http://docs.python.org/3.0/library/functions.html#open

提交回复
热议问题