【问题标题】:TypeError: can only concatenate list (not "str") to list create a script that concatenates valuesTypeError: can only concatenate list (not "str") to list 创建一个连接值的脚本
【发布时间】: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


【解决方案1】:

您不能将列表与字符串连接。

在您的代码中,linelist,而您正试图将其与 '\n'str 连接。我不知道您要在这里完成什么,但要使您的代码正常工作,您可以执行outfile.write('f{line}\n') 之类的操作。

我建议改用内置的json 模块。 Json 最适用于 listdict 包含 str 数据。

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

【讨论】:

  • 我把它放在你推荐的代码中。一切都保存到文件中,但结果,所有值都保存在一行中。而且我需要两列以及如何根据列表的表格。
  • 如果您可以包含输入和预期的输出输出,将会很有帮助
猜你喜欢
  • 2021-02-02
  • 2020-09-25
  • 2022-11-01
  • 1970-01-01
  • 2019-05-26
  • 1970-01-01
  • 2020-11-21
  • 2021-08-18
  • 2022-10-23
相关资源
最近更新 更多