python read函数的作用与使用方法

  • Post category:Python

Python内置的open()函数可以用来打开一个文件,并且返回一个文件对象(File object)。读取文件内容可以使用文件对象提供的read()方法。下面是read()方法的作用与详细使用方法的攻略。

read()方法的作用

read([n])方法可以从文件中读取n个字符的数据然后返回,如果没有给出n的值或者n为负数,则表示读取文件中的所有数据并返回。

read()方法的使用方法

file = open('example.txt', 'r')
content = file.read() # 读取文件中所有字符并返回
print(content)
file.close()

输出:

This is an example file.
It contains some text.
And this is the third line.

以上的代码中,我们首先用open()函数来打开example.txt文件,然后指定模式为读模式('r')。接着,我们调用read()方法并将其返回值赋值给变量content,这个变量包含了example.txt中的所有字符。最后我们使用print()函数输出文件的内容。需要注意的是,我们在读取完文件内容后需要调用close()方法来关闭文件对象。

读取指定数量的字符的示例:

file = open('example.txt', 'r')
content = file.read(10) # 读取文件中前10个字符
print(content)
file.close()

输出:

This is an

以上的代码中,我们读取了文件中前10个字符,并将结果输出到终端。