类型错误:强制转换为 Unicode:需要字符串或缓冲区,找到列表 [英] TypeError: coercing to Unicode: need string or buffer, list found

查看:37
本文介绍了类型错误:强制转换为 Unicode:需要字符串或缓冲区,找到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试启动并运行数据解析脚本.就数据操作而言,它是有效的.我想要做的是设置它,以便我可以使用单个命令输入多个用户定义的 CSV.

I'm trying to get a data parsing script up and running. It works as far as the data manipulation is concerned. What I'm trying to do is set this up so I can enter multiple user defined CSV's with a single command.

例如

> python script.py One.csv Two.csv Three.csv 

如果您对如何自动命名输出 CSV 有任何建议,以便如果 input = test.csv, output = test1.csv,我会也很感激.

If you have any advice on how to automate the naming of the output CSV so that if input = test.csv, output = test1.csv, I'd appreciate that as well.

获取

TypeError: coercing to Unicode: need string or buffer, list found

线

for line in csv.reader(open(args.infile)):

我的代码:

import csv
import pprint
pp = pprint.PrettyPrinter(indent=4)
res = []

import argparse
parser = argparse.ArgumentParser()

#parser.add_argument("infile", nargs="*", type=str)
#args = parser.parse_args()

parser.add_argument ("infile", metavar="CSV", nargs="+", type=str, help="data file") 
args = parser.parse_args()


with open("out.csv","wb") as f:
    output = csv.writer(f) 
    for line in csv.reader(open(args.infile)): 
        for item in line[2:]:

            #to skip empty cells
            if not item.strip():
                continue

            item = item.split(":")
            item[1] = item[1].rstrip("%")

            print([line[1]+item[0],item[1]])
            res.append([line[1]+item[0],item[1]])
            output.writerow([line[1]+item[0],item[1].rstrip("%")])

我真的不明白错误是怎么回事.有人可以通俗的解释一下吗?

I don't really understand what is going on with the error. Can someone explain this in layman's terms?

请记住,我是编程/python 的新手,基本上是一个人学习,所以如果可能的话,你能解释一下出了什么问题/如何修复它,以便我可以记下它以备将来参考.

Bear in mind I am new to programming/python as a whole and am basically learning alone, so if possible could you explain what is going wrong/how to fix it so I can note it for future reference.

推荐答案

args.infile 是一个文件名列表,而不是一个文件名.循环它:

args.infile is a list of filenames, not one filename. Loop over it:

for filename in args.infile:
    base, ext = os.path.splitext(filename)
    with open("{}1{}".format(base, ext), "wb") as outf, open(filename, 'rb') as inf:
        output = csv.writer(outf) 
        for line in csv.reader(inf): 

这里我使用了 os.path.splitext() 来分割扩展名和基本文件名,这样你就可以生成一个新的输出文件名,将 1 添加到基本文件名.

Here I used os.path.splitext() to split extension and base filename so you can generate a new output filename adding 1 to the base.

这篇关于类型错误:强制转换为 Unicode:需要字符串或缓冲区,找到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆