Python open(“文件”和“r”)返回的是什么类型

Python open(“文件”和“r”)返回的是什么类型,python,python-2.7,Python,Python 2.7,我正在尝试打开一个文件,读取它,然后拆分它 但是,我不知道如何将文件更改为字符串,当我运行这个小数据块时,它会给出一个AttributeError 有没有办法将此文件转换为字符串 into = open("file.in", "r") into = into.split() open()返回类型为file的对象 >>> type(open('file')) <type 'file'> 这将生成一个包含文件中所有单词的列表,因为split()按空格分割。如果需要行

我正在尝试打开一个文件,读取它,然后拆分它

但是,我不知道如何将文件更改为字符串,当我运行这个小数据块时,它会给出一个
AttributeError

有没有办法将此文件转换为字符串

into = open("file.in", "r")
into = into.split()
open()
返回类型为
file
的对象

>>> type(open('file'))
<type 'file'>
这将生成一个包含文件中所有单词的列表,因为
split()
按空格分割。如果需要行列表,请使用
readlines()

with open('file') as f:
    into = f.readlines()
请注意,更常见的用法是打开文件并使用
for
循环逐行迭代其内容:

with open('file') as f:
    for line in f:
        print line.split()    # for example

它返回一个文件对象,您可以使用
将其读入.read()
。这将返回一个包含文件内容的字符串,然后可以将其拆分为:
到.read().split()
。您也可以使用
对文件的行进行迭代,以便将行输入到:

您已经阅读了关于此的说明了吗?
with open('file') as f:
    for line in f:
        print line.split()    # for example