पायथन फाइल I / O: पायथन में फाइलें पढ़ें और लिखें

इस ट्यूटोरियल में, आप पायथन फाइल ऑपरेशंस के बारे में जानेंगे। अधिक विशेष रूप से, एक फ़ाइल खोलना, उससे पढ़ना, उसमें लिखना, उसे बंद करना, और विभिन्न फ़ाइल विधियाँ जिनसे आपको अवगत होना चाहिए।

वीडियो: पायथन में फाइलें पढ़ना और लिखना

फाइलें

संबंधित जानकारी संग्रहीत करने के लिए फ़ाइलों को डिस्क पर स्थानों का नाम दिया गया है। वे गैर-वाष्पशील मेमोरी (जैसे हार्ड डिस्क) में डेटा को स्थायी रूप से संग्रहीत करने के लिए उपयोग किया जाता है।

चूंकि रैंडम एक्सेस मेमोरी (रैम) अस्थिर है (जो कंप्यूटर बंद होने पर अपना डेटा खो देता है), हम डेटा के भविष्य के उपयोग के लिए फ़ाइलों को स्थायी रूप से संग्रहीत करके उपयोग करते हैं।

जब हम फ़ाइल से पढ़ना या लिखना चाहते हैं, तो हमें इसे पहले खोलने की आवश्यकता है। जब हमें किया जाता है, तो इसे बंद करने की आवश्यकता होती है ताकि फ़ाइल के साथ बंधे संसाधनों को मुक्त किया जा सके।

इसलिए, पायथन में, एक फ़ाइल ऑपरेशन निम्न क्रम में होता है:

  1. एक फ़ाइल खोलो
  2. पढ़ें या लिखें (ऑपरेशन करें)
  3. फ़ाइल बंद करें

पायथन में फाइलें खोलना

open()फ़ाइल खोलने के लिए पायथन में एक अंतर्निहित फ़ंक्शन होता है। यह फ़ंक्शन एक फ़ाइल ऑब्जेक्ट देता है, जिसे एक हैंडल भी कहा जाता है, क्योंकि इसका उपयोग फ़ाइल को तदनुसार पढ़ने या संशोधित करने के लिए किया जाता है।

 >>> f = open("test.txt") # open file in current directory >>> f = open("C:/Python38/README.txt") # specifying full path

हम फ़ाइल खोलते समय मोड निर्दिष्ट कर सकते हैं। मोड में, हम निर्दिष्ट करते हैं कि क्या हम फ़ाइल को पढ़ना r, लिखना wया जोड़ना aचाहते हैं। हम यह भी निर्दिष्ट कर सकते हैं कि क्या हम फाइल को टेक्स्ट मोड या बाइनरी मोड में खोलना चाहते हैं।

डिफ़ॉल्ट पाठ मोड में पढ़ रहा है। इस मोड में, हम फ़ाइल से पढ़ते समय स्ट्रिंग्स प्राप्त करते हैं।

दूसरी ओर, बाइनरी मोड बाइट्स लौटाता है और यह गैर-पाठ फ़ाइलों जैसे छवियों या निष्पादन योग्य फ़ाइलों के साथ काम करते समय उपयोग की जाने वाली मोड है।

मोड विवरण
r पढ़ने के लिए एक फ़ाइल खोलता है। (चूक)
w लिखने के लिए एक फ़ाइल खोलता है। एक नई फ़ाइल बनाता है यदि वह मौजूद नहीं है या मौजूद है तो फ़ाइल को काट देती है।
x अनन्य निर्माण के लिए एक फ़ाइल खोलता है। यदि फ़ाइल पहले से मौजूद है, तो कार्रवाई विफल हो जाती है।
a फ़ाइल के अंत में ट्रंक किए बिना फ़ाइल को खोलने के लिए खोलता है। यदि मौजूद नहीं है तो एक नई फ़ाइल बनाता है।
t पाठ मोड में खुलता है। (चूक)
b बाइनरी मोड में खुलता है।
+ अद्यतन (पढ़ने और लिखने) के लिए एक फ़ाइल खोलता है
 f = open("test.txt") # equivalent to 'r' or 'rt' f = open("test.txt",'w') # write in text mode f = open("img.bmp.webp",'r+b') # read and write in binary mode

अन्य भाषाओं के विपरीत, वर्ण a97 की संख्या को तब तक लागू नहीं करता है जब तक कि इसका उपयोग करके एन्कोडेड नहीं किया जाता है ASCII(या अन्य समकक्ष एन्कोडिंग)।

इसके अलावा, डिफ़ॉल्ट एन्कोडिंग प्लेटफॉर्म पर निर्भर है। खिड़कियों में, यह है cp1252, लेकिन utf-8लिनक्स में।

इसलिए, हमें डिफ़ॉल्ट एन्कोडिंग पर भी निर्भर नहीं होना चाहिए, अन्यथा हमारा कोड विभिन्न प्लेटफार्मों में अलग तरह से व्यवहार करेगा।

इसलिए, जब पाठ मोड में फ़ाइलों के साथ काम करते हैं, तो एन्कोडिंग प्रकार को निर्दिष्ट करने के लिए अत्यधिक अनुशंसा की जाती है।

 f = open("test.txt", mode='r', encoding='utf-8')

पायथन में फाइलें बंद करना

जब हम फ़ाइल पर ऑपरेशन कर रहे होते हैं, तो हमें फ़ाइल को ठीक से बंद करने की आवश्यकता होती है।

फ़ाइल बंद करने से संसाधन बंद हो जाएंगे जो फ़ाइल के साथ बंधे थे। यह close()पायथन में उपलब्ध विधि का उपयोग करके किया जाता है ।

पाइथन के पास अप्रतिबंधित वस्तुओं को साफ करने के लिए एक कचरा कलेक्टर है, लेकिन हमें फ़ाइल को बंद करने के लिए उस पर भरोसा नहीं करना चाहिए।

 f = open("test.txt", encoding = 'utf-8') # perform file operations f.close()

यह तरीका पूरी तरह से सुरक्षित नहीं है। यदि कोई अपवाद तब होता है जब हम फ़ाइल के साथ कुछ ऑपरेशन कर रहे हैं, तो कोड फ़ाइल को बंद किए बिना बाहर निकल जाता है।

एक सुरक्षित तरीका एक कोशिश… अंत में ब्लॉक का उपयोग करना है।

 try: f = open("test.txt", encoding = 'utf-8') # perform file operations finally: f.close()

इस तरह, हम गारंटी दे रहे हैं कि फ़ाइल को ठीक से बंद कर दिया गया है, भले ही कोई अपवाद उठाया गया हो जो प्रोग्राम प्रवाह को रोकने का कारण बनता है।

withस्टेटमेंट का उपयोग करके किसी फाइल को बंद करने का सबसे अच्छा तरीका है । यह सुनिश्चित करता है कि withस्टेटमेंट के अंदर ब्लॉक बाहर निकलने पर फाइल बंद हो।

हमें close()विधि को स्पष्ट रूप से कॉल करने की आवश्यकता नहीं है । यह आंतरिक रूप से किया जाता है।

 with open("test.txt", encoding = 'utf-8') as f: # perform file operations

पायथन में फाइलें लिखना

पायथन में एक फ़ाइल में लिखने के लिए, हमें इसे wलिखित, एपेंड aया अनन्य निर्माण xमोड में खोलने की आवश्यकता है।

हमें wमोड के साथ सावधान रहने की आवश्यकता है, क्योंकि यह फ़ाइल में ओवरराइट कर देगा यदि यह पहले से मौजूद है। इसके कारण, पिछले सभी डेटा मिटा दिए जाते हैं।

Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file.

 with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first file") f.write("This file") f.write("contains three lines")

This program will create a new file named test.txt in the current directory if it does not exist. If it does exist, it is overwritten.

We must include the newline characters ourselves to distinguish the different lines.

Reading Files in Python

To read a file in Python, we must open the file in reading r mode.

There are various methods available for this purpose. We can use the read(size) method to read in the size number of data. If the size parameter is not specified, it reads and returns up to the end of the file.

We can read the text.txt file we wrote in the above section in the following way:

 >>> f = open("test.txt",'r',encoding = 'utf-8') >>> f.read(4) # read the first 4 data 'This' >>> f.read(4) # read the next 4 data ' is ' >>> f.read() # read in the rest till end of file 'my first fileThis filecontains three lines' >>> f.read() # further reading returns empty sting ''

We can see that the read() method returns a newline as ''. Once the end of the file is reached, we get an empty string on further reading.

We can change our current file cursor (position) using the seek() method. Similarly, the tell() method returns our current position (in number of bytes).

 >>> f.tell() # get the current file position 56 >>> f.seek(0) # bring file cursor to initial position 0 >>> print(f.read()) # read the entire file This is my first file This file contains three lines

We can read a file line-by-line using a for loop. This is both efficient and fast.

 >>> for line in f:… print(line, end = '')… This is my first file This file contains three lines

In this program, the lines in the file itself include a newline character . So, we use the end parameter of the print() function to avoid two newlines when printing.

Alternatively, we can use the readline() method to read individual lines of a file. This method reads a file till the newline, including the newline character.

 >>> f.readline() 'This is my first file' >>> f.readline() 'This file' >>> f.readline() 'contains three lines' >>> f.readline() ''

Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading methods return empty values when the end of file (EOF) is reached.

 >>> f.readlines() ('This is my first file', 'This file', 'contains three lines')

Python File Methods

There are various methods available with the file object. Some of them have been used in the above examples.

Here is the complete list of methods in text mode with a brief description:

Method Description
close() Closes an opened file. It has no effect if the file is already closed.
detach() Separates the underlying binary buffer from the TextIOBase and returns it.
fileno() Returns an integer number (file descriptor) of the file.
flush() Flushes the write buffer of the file stream.
isatty() Returns True if the file stream is interactive.
read(n) Reads at most n characters from the file. Reads till end of file if it is negative or None.
readable() Returns True if the file stream can be read from.
readline(n=-1) Reads and returns one line from the file. Reads in at most n bytes if specified.
readlines(n=-1) Reads and returns a list of lines from the file. Reads in at most n bytes/characters if specified.
seek(offset,from=SEEK_SET) Changes the file position to offset bytes, in reference to from (start, current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
truncate(size=None) Resizes the file stream to size bytes. If size is not specified, resizes to current location.
writable() Returns True if the file stream can be written to.
write(s) स्ट्रिंग s को फ़ाइल में लिखता है और लिखे गए वर्णों की संख्या लौटाता है।
लेखन (लाइनें) फ़ाइल के लिए लाइनों की एक सूची लिखता है।

दिलचस्प लेख...