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


Python File readline()用法及代碼示例

文件 readline() 方法

readline() 方法是Python中的一個內置方法,用於從文件中獲取一行,使用該對象(當前文件流/IO對象)調用該方法並從文件中返回一行,我們也可以指定總數從行中讀取的字節數。

用法:

    file_object.readline(bytes)

參數:

  • bytes– 它是一個可選參數,可用於指定要從文件中讀取的總字節數。它的默認值是 -1 指定整行。

返回值:

這個方法的返回類型是<class 'str'>,它返回字符串。

範例1:

# Python File readline() Method with Example

# creating a file
myfile1 = open("hello1.txt", "w")

# writing content in the file
myfile1.write("Shivang, 21, Indore\n")
myfile1.write("Pankaj, 27, Mumbai\n")
myfile1.write("Rambha, 16, Heaven\n")

# closing the file
myfile1.close()

# reading the file (opening file in 'r' mode)
myfile1 = open("hello1.txt","r")

# reading and printing the file's content  
# line by line
print("file's content (using readline() method)...")
print("line1:", myfile1.readline())
print("line2:", myfile1.readline())
print("line3:", myfile1.readline())

# reading and printing the file's content
# all at once using read() method

# seeking the file position at 0th position
myfile1.seek(0)
print("file's content (using read() method)...")
print(myfile1.read())

# closing the file
myfile1.close()

輸出

file's content (using readline() method)...
line1: Shivang, 21, Indore

line2: Pankaj, 27, Mumbai

line3: Rambha, 16, Heaven

file's content (using read() method)...
Shivang, 21, Indore
Pankaj, 27, Mumbai
Rambha, 16, Heaven

範例2:

# Python File readline() Method with Example

# creating a file
myfile1 = open("hello1.txt", "w")

# writing content in the file
myfile1.write("Shivang, 21, Indore\n")
myfile1.write("Pankaj, 27, Mumbai\n")
myfile1.write("Rambha, 16, Heaven\n")

# closing the file
myfile1.close()

# reading the file (opening file in 'r' mode)
myfile1 = open("hello1.txt","r")

# reading and printing the file's content  
# line by line
print("file's content (using readline() method)...")
# reads whole line
print("line1:", myfile1.readline(-1))
# reads 5 bytes
print("line2:", myfile1.readline(5))
# reads next 10 bytes
print("line3:", myfile1.readline(10))

# closing the file
myfile1.close()

輸出

file's content (using readline() method)...
line1: Shivang, 21, Indore

line2: Panka
line3: j, 27, Mum


相關用法


注:本文由純淨天空篩選整理自 Python File readline() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。