首页 > 解决方案 > CSV Module: Issue with binary vs. string while trying to edit rows using dictionary

问题描述

Looking to edit rows in my csv document and I keep getting flip-flopping issues between requiring "bytes-like object is required" and "Error: iterator should return strings, not bytes"

Running Python3

I have tried changing the mode from "rb" to "r" as well as placing generic string texts in the writer.writerow loop.

The CSV file is definitely comma separated, not tab separated.

I am following this youtube tutorial: https://www.youtube.com/watch?v=pOJ1KNTlpzE&t=75s (1:40)

temp_file = NamedTemporaryFile(delete=False)


with open('clientlist.csv','rb') as csvfile, temp_file:
    reader = csv.DictReader(csvfile)
    fieldnames = ['Account Name','Account Number','Date Last Checked']
    writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
    writer.writeheader()
    print(temp_file.name)
    for row in reader:
        writer.writerow({
                'Account Name': row['Account Name'],
                'Account Number': row['Account Number'],
                'Date Last Checked': row['Date Last Checked'],
            })

#shutil.move(temp_file.name, client_list)

Expected result should make it when I open the temp_file there is data. Then, from what I read, the shuthil should copy it. Right now the temp_file is blank.

Any ideas if it would be easier to start from scratch and use numpy or pandas? Saw this video on that: https://www.youtube.com/watch?v=pbjGo3oj0PM&list=PLulVrUACBIGX8JT7vpoHVQLYqgOKeunb6&index=16&t=0s

标签: python

解决方案


根据NamedTemporaryFile文档,命名临时文件w+b默认以模式打开 - 即二进制文件。

由于您正在读取和写入 csv 文件,因此(对我而言)以二进制模式操作毫无意义,所以宁可在模式下打开输入文件r,并在模式下请求一个临时文件w

import csv
import tempfile

temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False) # note the mode argument

with open('clientlist.csv','r') as csvfile, temp_file:  #note the mode argument
    reader = csv.DictReader(csvfile)
    fieldnames = ['Account Name','Account Number','Date Last Checked']
    writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
    writer.writeheader()
    for row in reader:
        writer.writerow({
            'Account Name': row['Account Name'],
            'Account Number': row['Account Number'],
            'Date Last Checked': row['Date Last Checked'],
        })

这似乎适合我。


推荐阅读