修复Python中的错误 AttributeError: ‘_io.TextIOWrapper’ object has no attribute ‘split’ 

属性是与对象或类相关的值。当你调用一个对象的属性,而该对象的类型不被方法支持时,就会出现Python AttributeError

例如,在split()上使用_io.TextIOWrapper方法会返回AttributeError,因为_io.TextIOWrapper对象不支持split()方法。

本教程将教你修复Python中的AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

修复Python中的错误 AttributeError: '_io.TextIOWrapper' object has no attribute 'split' 

下面的命令对打开的文件对象使用split()方法。

f=open('test.txt')
f.split()

输出:

 

python attribute error has no attribute split

 

它返回AttributeError,因为split()方法不是类_io.TextIOWrapper的属性。String类提供了split()方法来将字符串拆分为列表。

您可以使用for循环修复此错误。

f=open('test.txt')
for line in f:
	line.split()

它不会返回任何错误,因为文件对象中的每一行都是一个字符串。

您还可以使用类_io.TextIOWrapper中的方法将文件对象转换为字符串。

  1. read() -此方法读取文件内容并将其作为字符串返回。
  2. readline() -它读取文件中的一行并将其作为字符串返回。
  3. readlines() -此方法有助于逐行读取文件内容,并将其作为字符串列表返回。

然后你可以调用split()方法而不需要得到AttributeError

f=open('test.txt')
str=f.read()
str.split()

现在你知道如何在Python中解决AttributeError了。我们希望您发现这篇文章有帮助。

修复Python中的错误 AttributeError: '_io.TextIOWrapper' object has no attribute 'split'