python 示例
文件read()方法 (File read() Method)
read() method is an inbuilt method in Python, it is used to read the content of the file, by using this method we can read the specified number of bytes from the file or content of the whole file.
read()方法是Python中的内置方法,用于读取文件的内容,通过使用此方法,我们可以从文件或整个文件的内容中读取指定数目的字节。
Syntax:
句法:
file_object.read(size)
Parameter(s):
参数:
size – It is an optional parameter, it specifies the number of bytes to be read from the file. It's default value is -1 that returns the content of the whole file.
size –这是一个可选参数,它指定要从文件读取的字节数。 它的默认值是-1 ,它返回整个文件的内容。
Return value:
返回值:
The return type of this method is <class 'str'>, it returns the string i.e. file's content (if the file is in text mode).
此方法的返回类型为<class'str'> ,它返回字符串,即文件的内容(如果文件处于文本模式)。
Example:
例:
# Python File read() Method with Example
# creating a file
myfile = open("hello.txt", "w")
# wrting text to the file
myfile.write("C++ is a popular programming language.")
# closing the file
myfile.close()
# reading the file i.e. opening file in read mode
myfile = open("hello.txt", "r")
# reading & printing the whole file
# Here, we are not specifying the size
print("myfile.read()...")
print(myfile.read())
# reset the position
myfile.seek(0)
# reading 10 bytes and printing
print("myfile.read(10)...")
print(myfile.read(10))
# reset the position
myfile.seek(0)
# reading whole file by passing -1
print("myfile.read(-1)...")
print(myfile.read(-1))
# closing the file
myfile.close()
Output
输出量
myfile.read()...
C++ is a popular programming language.
myfile.read(10)...
C++ is a p
myfile.read(-1)...
C++ is a popular programming language.
翻译自: https://www.includehelp.com/python/file-read-method-with-example.aspx
python 示例