2016-12-13 33 views
-2

我有以下代碼:在文件Python中保存字符串時出錯?

print(title) 
f = io.open("1.txt", "a", encoding="utf-8") 
f.write(title + '\n') 
f.close() 

我得到錯誤:

TypeError('can only concatenate list (not "str") to list',))

我使用Python 3.5

+0

你可以提供更多的上下文嗎?什麼是變量'title',哪一行是發生錯誤? –

+0

'標題'是字符串作爲'致命的戰鬥' – Griboedov

+1

'title'seems是一個列表,而不是一個字符串。你應該提供'title''這一行來表示它在問題中的價值,所以我們可以看到什麼是錯的,以及如何解決它。 –

回答

1

您可以將使用列表中的連接功能轉換爲字符串:

" ".join(["This", "is", "a", "list", "of", "strings"]) 
>>> This is a list of strings 

在Python中,我們通常使用「with-syntax」來編寫/讀取文件:

with open('workfile.txt', 'w') as f: 
    f.write("My entry line\n") 
    f.write(" ".join(["Other", "line", "here"])) 
    f.write("\n") 
+0

所以,我有字符串,而不是'list' – Griboedov

+0

你是說在你的Python解釋器中,''string 1「+」string 2「'會引發一個'TypeError'異常嗎? –

+0

似乎它發生在這裏:'f.write(url +'\ n')' – Griboedov

1

title是一個string類型的變量嗎?

您的代碼不出現錯誤運行在這個例子中:

import io 
title = "My Title" 
print(title) 
f = io.open("1.txt", "a", encoding="utf-8") 
f.write(title + '\n') 
f.close() 

爲了節省您可以通過書面形式投title到字符串:

str(title) 

可以檢查變量的類型爲字符串,這個方式:

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

如果您碰巧有一個列表作爲輸入,請參考解決方案由Jeanderson BarrosCândido建議。

+0

我輸入了'title(標題)'並得到了', – Griboedov

+0

你能告訴我們你把'title'設置爲一個值嗎? 難道是你的問題中的錯誤信息引用腳本中的另一行? –

相關問題