Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

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

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.

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...