Python 类型错误:强制转换为 Unicode:需要字符串或缓冲区,找到列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21580270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:11:25  来源:igfitidea点击:

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

pythonpython-2.7argparse

提问by user3234810

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.

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

e.g.

例如

> python script.py One.csv Two.csv Three.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.

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

Getting

得到

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

for the line

对于线

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

My code:

我的代码:

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?

我真的不明白错误是怎么回事。有人可以用外行的术语解释这一点吗?

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.

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

采纳答案by Martijn Pieters

args.infileis a listof filenames, not one filename. Loop over it:

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

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): 

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

在这里,我曾经os.path.splitext()拆分扩展名和基本文件名,以便您可以生成添加1到基本文件名的新输出文件名。

回答by Wooble

If you specify an nargsargument to .add_argument, the argument will always be returned as a list.

如果您为 指定nargs参数.add_argument,则该参数将始终作为列表返回。

Assuming you want to deal with all of the files specified, loop through that list:

假设您要处理指定的所有文件,请遍历该列表:

for filename in args.infile:
    for line in csv.reader(open(filename)): 
        for item in line[2:]:

            #to skip empty cells
[...]

Or if you really just want to be able to specify a single file; just get rid of nargs="+".

或者,如果您真的只想指定一个文件;刚刚摆脱nargs="+"