readline() Function (readline() Method) :-
readline() Method का उपयोग File से एक बार में एक Line Read करने के लिए किया जाता है। इसे बार-बार Call करने पर अगली Line Read होती है।
English: The readline() method is used to read one line at a time from a file. Each successive call reads the next line.
Syntax:
file.readline()
Example 1: पहली Line Read करना
मान लीजिए demo.txt में Data है:
Hello Python
Welcome to File Handling
Python is Easy
Python Program:
file = open("demo.txt", "r", encoding="utf-8")
data = file.readline()
print(data, end="")
file.close()
Output:
Hello Python
Explanation:
-
readline() पहली Line Read करता है।
-
यह सामान्यतः Line के अंत में मौजूद Newline Character (\n) को भी Return करता है।
-
end="" अतिरिक्त Newline Print होने से रोकता है।
Example 2: दो Lines Read करना
file = open("demo.txt", "r", encoding="utf-8")
line1 = file.readline()
line2 = file.readline()
print(line1, end="")
print(line2, end="")
file.close()
Output:
Hello Python
Welcome to File Handling
Explanation:
-
पहली बार readline() पहली Line Read करता है।
-
दूसरी बार readline() दूसरी Line Read करता है।
-
हर बार File Pointer अगली Line पर पहुँच जाता है।
Example 3: File में कोई Line न बचने पर
जब File की सभी Lines Read हो जाती हैं, तब अगली बार readline() Call करने पर Empty String ('') Return होती है।
file = open("demo.txt", "r", encoding="utf-8")
print(file.readline(), end="")
print(file.readline(), end="")
print(file.readline(), end="")
result = file.readline()
print(result == "")
file.close()
Output:
Hello Python
Welcome to File Handling
Python is Easy
True
Important Points:
-
readline() एक बार में एक Line Read करता है।
-
इसे बार-बार Call करने पर अगली Line मिलती है।
-
यह String (str) Return करता है।
-
File समाप्त होने पर Empty String ('') Return करता है।