对Python read()和open()函数的了解加深

时间:2019-01-21 16:49:08

标签: python python-3.x

在使用Python 3.7的同时使用read()和open()函数

是否有记录open()但没有记录read()的原因?

https://docs.python.org/3.7/library/functions.html

from sys import argv

script, filename = argv

txt = open(filename)

print(f"Here's your file {filename}:")
print(txt.read())

print("Type the filename again:")
file_again = input("> ")

txt_again = open(file_again)

print(txt_again.read())

4 个答案:

答案 0 :(得分:5)

因为read不是内置的function,而是method*IO* / *Reader中的file object

您可以找到此类read方法的文档:io.RawIOBase.readio.BufferedIOBase.readio.BufferedReader.readio.TextIOBase.read,...

答案 1 :(得分:4)

因为read()不是内置函数,因为它不以builtins.read的形式出现。相反,它是_io.BufferedReader类的方法。这意味着您必须创建该类的对象(通常使用内置函数open()),然后为该对象调用read()

答案 2 :(得分:0)

因为read()file-object的一种方法

答案 3 :(得分:0)

read不是其他人所说的Python。您可以在许多I / O对象(例如文件对象,http请求等)中找到该方法。