當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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