python - 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
解决方案
根据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'],
})
这似乎适合我。
推荐阅读
- java - 当我以横向/反向横向启动 Activity 时,Android webrtc SurfaceViewRenderer 预览变为空白
- javascript - Material UI - 单击搜索图标时未单击搜索栏中的文本字段
- algorithm - 递归构建堆的自顶向下算法
- android - Android:如何检测 workmanager 已经处于入队模式多长时间?
- ansible - Ansible 变量中定义的值的带引号或不带引号之间的区别
- google-chrome - 有什么方法可以禁用 chrome 严格的 MIME 检查
- google-cloud-platform - GCP 上带有日期的文件夹名称
- javascript - 在 Jest 的类服务中断言做什么
- flutter - 如何在颤动中全屏制作耀斑动画?
- java - Eclipse Java 格式化程序