अन्य भाषाओं की तरह, पायथन फाइलों को पढ़ने, लिखने या एक्सेस करने के लिए कुछ इनबिल्ट फ़ंक्शन प्रदान करता है। पायथन मुख्य रूप से दो प्रकार की फाइलों को संभाल सकता है। सामान्य टेक्स्ट फ़ाइल और बाइनरी फ़ाइलें।
टेक्स्ट फ़ाइलों के लिए, प्रत्येक पंक्ति को एक विशेष वर्ण '\n' के साथ समाप्त किया जाता है (इसे ईओएल या एंड ऑफ़ लाइन के रूप में जाना जाता है)। बाइनरी फ़ाइल के लिए, कोई पंक्ति समाप्ति वर्ण नहीं है। यह सामग्री को बिट स्ट्रीम में बदलने के बाद डेटा बचाता है।
इस खंड में हम टेक्स्ट फाइलों के बारे में चर्चा करेंगे।
फाइल एक्सेस करने के तरीके
| Sr.No | मोड और विवरण |
|---|---|
| 1 | <टीडी>|
| 2 | <टीडी>|
| 3 | <टीडी>|
| 4 | <टीडी>|
| 5 | <टीडी>|
| 6 | <टीडी>
अब देखें कि राइटलाइन () और राइट () मेथड का उपयोग करके फाइल को कैसे लिखा जा सकता है।
उदाहरण कोड
#Create an empty file and write some lines
line1 = 'This is first line. \n'
lines = ['This is another line to store into file.\n',
'The Third Line for the file.\n',
'Another line... !@#$%^&*()_+.\n',
'End Line']
#open the file as write mode
my_file = open('file_read_write.txt', 'w')
my_file.write(line1)
my_file.writelines(lines) #Write multiple lines
my_file.close()
print('Writing Complete')
आउटपुट
Writing Complete
पंक्तियाँ लिखने के बाद, हम फ़ाइल में कुछ पंक्तियाँ जोड़ रहे हैं।
उदाहरण कोड
#program to append some lines
line1 = '\n\nThis is a new line. This line will be appended. \n'
#open the file as append mode
my_file = open('file_read_write.txt', 'a')
my_file.write(line1)
my_file.close()
print('Appending Done')
आउटपुट
Appending Done
अंत में, हम देखेंगे कि रीड () और रीडलाइन () विधि से फ़ाइल सामग्री को कैसे पढ़ा जाए। हम पहले 'n' वर्ण प्राप्त करने के लिए कुछ पूर्णांक संख्या 'n' प्रदान कर सकते हैं।
उदाहरण कोड
#program to read from file
#open the file as read mode
my_file = open('file_read_write.txt', 'r')
print('Show the full content:')
print(my_file.read())
#Show first two lines
my_file.seek(0)
print('First two lines:')
print(my_file.readline(), end = '')
print(my_file.readline(), end = '')
#Show upto 25 characters
my_file.seek(0)
print('\n\nFirst 25 characters:')
print(my_file.read(25), end = '')
my_file.close()
आउटपुट
Show the full content: This is first line. This is another line to store into file. The Third Line for the file. Another line... !@#$%^&*()_+. End Line This is a new line. This line will be appended. First two lines: This is first line. This is another line to store into file. First 25 characters: This is first line. This