Important Notice:

Reading a Specific Number of Characters

Reading a Specific Number of Characters

3 views 1 min read

Reading a Specific Number of Characters (निश्चित Characters पढ़ना) :-

 Python में read() Method के अंदर Number देकर File से निश्चित संख्या में Characters Read किए जा सकते हैं।

English: Reading a Specific Number of Characters means reading only the specified number of characters from a file using the read(size) method.

Syntax: file.read(number)

यहाँ number उन Characters की संख्या बताता है जिन्हें Read करना है।

Example 1: पहले 5 Characters पढ़ना

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

Hello Python

Python Program:

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

data = file.read(5)

print(data)

file.close()

Output:

Hello

Explanation:

  • read(5) File से पहले 5 Characters Read करता है।

  • इसमें H, e, l, l, o शामिल हैं।

  • बाकी Data Read नहीं होता।

Example 2: अलग-अलग बार Characters Read करना

file = open("demo.txt", "r", encoding="utf-8")
print(file.read(5))
print(file.read(6))
file.close()

मान लीजिए File Content:

Hello Python

Output:

Hello
 Pytho

 

Explanation:

  • पहला read(5) पाँच Characters Read करता है।

  • File Pointer पाँच Characters आगे चला जाता है।

  • दूसरा read(6) अगली छह Characters Read करता है।

  • इसलिए दूसरी बार Reading वहीं से शुरू होती है जहाँ पहली बार समाप्त हुई थी।

Example 3: उपलब्ध Characters से अधिक Number देना

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

 

data = file.read(50)

 

print(data)

 

file.close()

यदि File में केवल Hello Python लिखा है, तो Output होगा:

Hello Python

 

Explanation: यदि माँगे गए Characters की संख्या File में उपलब्ध Characters से अधिक है, तो read() केवल उपलब्ध Data Read करता है।

Important Points:

  1. read(5) का अर्थ है 5 Characters Read करना।

  2. Text Mode में Size Characters की संख्या बताता है।

  3. read() के बाद File Pointer आगे बढ़ जाता है।

  4. File के अंत तक पहुँचने पर आगे read() करने पर Empty String मिलती है।

Related Notes