文件 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 readable()用法及代码示例
- Python File readlines()用法及代码示例
- Python File readline()用法及代码示例
- Python File tell()用法及代码示例
- Python File seek()用法及代码示例
- Python File flush()用法及代码示例
- Python File write()用法及代码示例
- Python File truncate()用法及代码示例
- Python File fileno()用法及代码示例
- Python File open()用法及代码示例
- Python File isatty()用法及代码示例
- Python File writable()用法及代码示例
- Python File writelines()用法及代码示例
- Python File close()用法及代码示例
- Python File seekable()用法及代码示例
- Python numpy.less()用法及代码示例
- Python Sympy Permutation.list()用法及代码示例
- Python Matplotlib.figure.Figure.subplots_adjust()用法及代码示例
- Python numpy.tril()用法及代码示例
- Python Matplotlib.pyplot.matshow()用法及代码示例
注:本文由纯净天空筛选整理自 Python File read() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。