Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.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:AttributeError:'_io.TextIOWrapper';对象没有属性';拆分';_Python_Python 3.x - Fatal编程技术网

Python:AttributeError:'_io.TextIOWrapper';对象没有属性';拆分';

Python:AttributeError:'_io.TextIOWrapper';对象没有属性';拆分';,python,python-3.x,Python,Python 3.x,我有一个文本文件,我们称它为goodlines.txt,我想加载它并制作一个包含文本文件中每一行的列表 我试着像这样使用split()过程: >>> f = open('goodlines.txt') >>> mylist = f.splitlines() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: '_

我有一个文本文件,我们称它为
goodlines.txt
,我想加载它并制作一个包含文本文件中每一行的列表

我试着像这样使用
split()
过程:

>>> f = open('goodlines.txt')
>>> mylist = f.splitlines()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: '_io.TextIOWrapper' object has no attribute 'splitlines'
>>> mylist = f.split()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: '_io.TextIOWrapper' object has no attribute 'split'
>f=open('goodlines.txt'))
>>>mylist=f.splitlines()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:“\u io.TextIOWrapper”对象没有属性“splitlines”
>>>mylist=f.split()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:“\u io.TextIOWrapper”对象没有属性“split”
为什么会出现这些错误?这不是我使用split()的方式吗?(我正在使用python 3.3.2)

试试这个:

 >>> f = open('goodlines.txt')
 >>> mylist = f.readlines()

open()
函数返回一个文件对象。对于file对象,没有类似于
splitlines()
split()
的方法。您可以使用
dir(f)
查看文件对象的所有方法。

您没有读取文件内容:

my_file_contents = f.read()
有关更多信息,请参阅

您可以不调用
read()
readlines()
在文件对象上循环:

f = open('goodlines.txt')
for line in f:
    print(line)
with open('goodlines.txt') as f:
    mylist = list(f)
如果您想从中获得一个列表(没有您要求的
\n


您正在对打开的文件对象使用
str
方法

只需在文件对象上调用
list()
,即可将文件作为行列表读取:

f = open('goodlines.txt')
for line in f:
    print(line)
with open('goodlines.txt') as f:
    mylist = list(f)
这不包括换行符。您可以在列表中删除这些内容:

with open('goodlines.txt') as f:
    mylist = [line.rstrip('\n') for line in f]

这很好,但我在每次结束时都会得到这些“\n”东西。。。如何在不更改文本文件的情况下删除它们?列表理解不会删除换行符。您也可以只调用
list(f)
,效果与您当前的代码相同。@samuele mattiuzzo“my_list=[f中的行对行]”也在每个列表的末尾列出了\n,即使它不在文本文件中。但阅读时是否应该拆分工作?正如皮特斯先生迅速指出的那样,
\n
无论如何都需要剥离。