当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python File read()用法及代码示例


文件 read() 方法

read()方法是Python内置的方法,用于读取文件的内容,通过该方法我们可以从文件中读取指定字节数或整个文件的内容。

用法:

    file_object.read(size)

参数:

  • size– 它是一个可选参数,它指定要从文件中读取的字节数。默认值为 -1,返回整个文件的内容。

返回值:

这个方法的返回类型是<class 'str'>,它返回字符串,即文件的内容(如果文件处于文本模式)。

例:

# 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()

输出

myfile.read()...
C++ is a popular programming language.
myfile.read(10)...
C++ is a p
myfile.read(-1)...
C++ is a popular programming language.


相关用法


注:本文由纯净天空筛选整理自 Python File read() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。