Important Notice:

read() Function (read() Method)

read() Function (read() Method)

3 views 2 min read

read() Function (read() Method) :-

read()  Method का उपयोग File से Data Read करने के लिए किया जाता है। यदि इसमें कोई Argument नहीं दिया जाता है, तो यह File Pointer की Current Position से लेकर File के अंत तक पूरा Remaining Data Read करता है।

English: The read() method is used to read data from a file. Without an argument, it reads all remaining content from the current file position to the end of the file.

Syntax:

file.read()

या

file.read(size)

यहाँ:

file – File Object है।

read() – File से Data Read करने का Method है।

size – कितने Characters Read करने हैं, यह बताता है।

Example 1: बिना Argument के read()

मान लीजिए demo.txt में यह Data है:

Hello Python
Welcome

Python Program:

file = open("demo.txt", "r", encoding="utf-8")

data = file.read()

print(data)

file.close()

Output:

Hello Python
Welcome

Explanation: read() में कोई Argument नहीं दिया गया है, इसलिए File का पूरा Remaining Data Read हो जाता है।

Arguments of read() Method in Python
 
Python में read() method एक optional argument size लेता है। इसका उपयोग यह निर्धारित करने के लिए किया जाता है कि File से कितने characters पढ़ने हैं।

Syntax:
file.read(size)
  • size – Specifies the number of characters to read from the file.

  • यदि size नहीं दिया जाता है, तो पूरी file पढ़ी जाती है।

  • यदि size = 5 दिया जाता है, तो केवल पहले 5 characters पढ़े जाते हैं।


 
Example:
 
file = open("demo.txt", "r")

print(file.read(5))

file.close()

Output (demo.txt):
 
Hello

Note: Text mode में read(size) characters पढ़ता है, जबकि Binary mode में यह bytes पढ़ता है।
 
Example 2: read() का Return Type
 
file = open("demo.txt", "r", encoding="utf-8")

data = file.read()

print(type(data))

file.close()

Output:

<class 'str'>

Explanation: Text Mode में read() Method Data को String (str) के रूप में Return करता है।

Example 3: Empty File Read करना

यदि File खाली है, तो read() Empty String Return करता है।

file = open("empty.txt", "r", encoding="utf-8")

data = file.read()

print(data == "")

file.close()

Output:

True

Explanation: empty.txt में कोई Data नहीं है, इसलिए read() Empty String ('') Return करता है।

Related Notes