Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python文件中保存字符串时出错?_Python_Python 3.x - Fatal编程技术网

在Python文件中保存字符串时出错?

在Python文件中保存字符串时出错?,python,python-3.x,Python,Python 3.x,我有以下代码: print(title) f = io.open("1.txt", "a", encoding="utf-8") f.write(title + '\n') f.close() 我得到一个错误: TypeError('只能将列表(而不是“str”)连接到列表',)) 我使用Python 3.5您可以使用连接函数将列表转换为字符串: " ".join(["This", "is", "a", "list", "of", "strings"]) >>> This i

我有以下代码:

print(title)
f = io.open("1.txt", "a", encoding="utf-8")
f.write(title + '\n')
f.close()
我得到一个错误:

TypeError('只能将列表(而不是“str”)连接到列表',))


我使用Python 3.5

您可以使用连接函数将列表转换为字符串:

" ".join(["This", "is", "a", "list", "of", "strings"])
>>> This is a list of strings
在Python中,我们通常使用“with syntax”编写/读取文件:


title
是字符串类型的变量吗

在此示例中,您的代码运行时没有错误:

import io
title = "My Title"
print(title)
f = io.open("1.txt", "a", encoding="utf-8")
f.write(title + '\n')
f.close()
要保存,您可以通过以下方式将
标题
转换为字符串:

str(title)
您可以通过以下方式检查字符串的变量类型:

if type(title) is str:
    print("It's a string")

如果您碰巧有一个列表作为输入,请参考Jeanderson Barros C–ndido建议的解决方案。

那么,我有字符串,而不是
列表
您是说在Python解释器中,
“string 1”+“string 2”
将引发
类型错误
异常?似乎发生在这里:
f.write(url+'\n'))
您的问题/假设中一定缺少某些内容。。。。如果您真的使用了2个字符串,则永远不会出现此错误。您能告诉我们将
title
设置为值的行吗?您问题中的错误消息是否指向脚本中的另一行?您必须将其转换为字符串类型。您可以提供更多上下文吗?变量
title
是什么,错误发生在哪一行?
title
似乎是一个列表而不是字符串。您应该在问题中提供“title”获取其值的行,这样我们就可以看到哪里出了问题以及如何解决问题。您可以尝试
print(type(title))
。但是既然你有代码,就分享吧。如果你认为它是一个字符串,但它不是,那么
title
的定义可能会有错误。这对我很有用。
title
不是字符串,或者您对导致错误的行做出了错误的假设。
if type(title) is str:
    print("It's a string")