Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - TypeError: can only concatenate list (not "str") to list create a script that concatenates values

I am trying to create a script that concatenates values in files into columns. But unfortunately I get an error: "TypeError: can only concatenate list (not" str ") to list"

What am I doing wrong?

import re
inputList = []
for file in ['text1.txt','text2.txt']:
    with open(file,'r') as infile:
        k = 0
        for line in infile:
            i = 0
            if i < len(inputList) and k:
                inputList[i].extend(re.sub('[^A-Za-z0-9,]+', '', line).split(","))
            else :
                inputList.append(re.sub('[^A-Za-z0-9,]+', '', line).split(","))
            i += 1
        k = 1
print(inputList)
with open('text3','w') as outfile:
    for line in inputList:
        outfile.write(line + '
')
question from:https://stackoverflow.com/questions/65839209/typeerror-can-only-concatenate-list-not-str-to-list-create-a-script-that-co

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

1 Answer

0 votes
by (71.8m points)

You can not concatenate list with string.

In your code line is list and you are trying to concatenate it with ' ' a str. I don't know what You are trying to acomplish here but for your code to work you can do something like outfile.write('f{line} ').

I would recommend using built-in json module instead. Json works best with list or dict containg str data.

import json
with open('text3','w') as outfile:
    json.dump(inputList, outfile)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...