文件 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。