Python फ़ाइलों, ऑब्जेक्ट्स को संभालने और विभिन्न एप्लिकेशन बनाने में सक्षम है। हम पूरी तरह से फीचर्ड एप्लिकेशन बनाने और विकसित करने के लिए Python के एक्सटेंशन और पैकेज का उपयोग कर सकते हैं।
मान लीजिए आप अपने सिस्टम में फ़ाइलों को नियंत्रित करना चाहते हैं; तो Python एक OS मॉड्यूल प्रदान करता है जिसमें सिस्टम-सक्षम कार्यक्षमताएं होती हैं जो आपको ऑपरेटिंग सिस्टम में फ़ाइलों के साथ इंटरैक्ट करने की अनुमति देती हैं।
आइए देखें कि Python में OS मॉड्यूल का उपयोग करके फ़ोल्डर से एकाधिक टेक्स्ट फ़ाइलें कैसे पढ़ें।
अपने नोटबुक में OS मॉड्यूल इम्पोर्ट करें।
वह पथ परिभाषित करें जहां आपके सिस्टम में टेक्स्ट फ़ाइलें स्थित हैं।
फ़ाइलों की सूची बनाएं और यह पता लगाने के लिए पुनरावृति करें कि क्या उन सभी में सही एक्सटेंशन है या नहीं।
मॉड्यूल में परिभाषित फंक्शन का उपयोग करके फ़ाइलें पढ़ें।
उदाहरण
# आवश्यक लाइब्रेरी आयात करें
import os
# डायरेक्टरी का स्थान परिभाषित करें
path =r"C:/Users/Sairam/Documents/"
# डायरेक्टरी बदलें
os.chdir(path)
def read_files(file_path):
with open(file_path, 'r') as file:
print(file.read())
# डायरेक्टरी में सभी फ़ाइलों पर पुनरावृति करें
for file in os.listdir():
if file.endswith('.txt'):
# विशेष फ़ाइल का फाइलपथ बनाएं
file_path =f"{path}/{file}"
read_files(file_path)
आउटपुट
Sample 1 ========
Welcome to Tutorialspoint.
You are browsing the best resource for Online Education.
Sample 2 ========
A distributed ledger is a type of data structure which resides across multiple computer devices, generally spread across locations or regions. Distributed ledger technology (DLT) includes blockchain technologies and smart contracts. While distributed ledgers existed prior to Bitcoin, the Bitcoin blockchain marks the convergence of a host of technologies, including timestamping of transactions, Peer-to-Peer (P2P) networks, cryptography, and shared computational power, along with a new consensus algorithm.
निर्दिष्ट स्थान पर हमारे पास दो टेक्स्ट फ़ाइलें हैं और प्रोग्राम इन दोनों फ़ाइलों की सामग्री पढ़कर कंसोल पर टेक्स्ट प्रदर्शित करता है।