【发布时间】:2021-04-26 13:39:34
【问题描述】:
我正在尝试创建一个将文件中的值连接到列中的脚本。但不幸的是我收到一个错误:“TypeError: can only concatenate list (not" str ") to list"
我做错了什么?
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 + '\n')
【问题讨论】:
-
我猜,错误不是因为当前代码。你能指定哪一行出错吗?它将在您的错误消息中指定。
-
@Rahul 不幸的是,错误发生在第 17 行。“ 回溯(最后一次调用):文件“D:\script.py”,第 17 行,在
outfile.write(line + '\n') TypeError: can only concatenate list (not "str") to list" -
知道了。这是有道理的。
标签: python python-3.x list python-2.7 python-requests