Python:无法将“列表”对象隐式转换为str

时间:2018-09-06 01:23:38

标签: python

我正在尝试读取一个名为 differences.txt 的文件,并将其放入一行变量中。

这是 differences.txt

192.168.0.***
192.168.0.***

和我的代码:

with open ("/home/pi/Documents/difference.txt") as myfile:
    difip=myfile.readlines()
    print (difip)

和我的错误:

Traceback (most recent call last):
File "/home/pi/Desktop/clean.py", line 95, in <module>
body = "Different IP's:" + difip
TypeError: Can't convert 'list' object to str implicitly

任何帮助都会很棒!谢谢!

1 个答案:

答案 0 :(得分:1)

myfile.readlines() 

返回文件的行列表 (请记住,其中包括\ n用于换行)。您的情况是返回

    ["192.168.0.***\n", "192.168.0.***\n"]

选项1)您应该改用strip()函数

myfile = open('/home/pi/Documents/difference.txt', 'r')
text = myfile.read().strip() #pass ("\n") as argument to strip() to remove the newlines.

选项2)(可选)您可以使用相同的代码,但按如下所示修改最后一行:

with open ("/home/pi/Documents/difference.txt") as myfile:
    difip=myfile.readlines()
print (difip[0] + difip[1])

此错误消息

TypeError: Can't convert 'list' object to str implicitly

告诉您您正在尝试将列表打印为字符串。最后的更改是打印存储在文本文件的前两行中的字符串。

相关问题