पायथन स्टडीओ के फॉपेन फ़ंक्शन का उपयोग करता है और मोड को तर्क के रूप में पास करता है। मुझे लगता है कि आप खिड़कियों का उपयोग करते हैं, क्योंकि @Lev का कहना है कि कोड लिनक्स पर ठीक काम करता है।
When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for "update"). However, when you switch between reading and writing, there must be an intervening fflush, fsetpos, fseek, or rewind operation. The current position can be specified for the fsetpos or fseek operation, if desired.
तो, समाधान file.write()
कॉल करने से पहले file.seek()
जोड़ने के लिए है:
निम्नलिखित खिड़कियों के fopen प्रलेखन से है, यह आपकी समस्या को हल करने के लिए एक संकेत हो सकता है। फ़ाइल के अंत में जोड़ने के लिए, file.seek(0, 2)
का उपयोग करें।
To change the file object’s position, use f.seek(offset, from_what). The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point.
[संदर्भ: http://docs.python.org/tutorial/inputoutput.html]
टिप्पणियों और @Burkhan उसके जवाब में में @lvc से उल्लेख किया है, आप उपयोग कर सकते हैं नए
आपके संदर्भ के लिए, file.seek इस प्रकार काम करता है io module से खुला कार्य। हालांकि, मैं करते रहे कि लिखने समारोह इस मामले में बिल्कुल वैसा ही काम नहीं करता चाहते हैं - आप यूनिकोड तार इनपुट के रूप में [आप अपने मामले में स्ट्रिंग के लिए एक u
उपसर्ग] प्रदान करने की आवश्यकता:
from io import open
fil = open('text.txt', 'a+')
fil.write('abc') # This fails
fil.write(u'abc') # This works
अंत में, कृपया 'फ़ाइल' नाम का उपयोग एक परिवर्तनीय नाम के रूप में करने से बचें, क्योंकि यह एक बिल्टिन प्रकार को संदर्भित करता है और चुपचाप ओवर-लिखित होगा, जिससे त्रुटियों को स्पॉट करने में कुछ मुश्किल होती है।
से
open
उपयोग करने के लिए आप कहाँ त्रुटि मिलती हैं? समस्या यह प्रतीत होती है कि आप एपेंड मोड – Dharaमें खोले गए फ़ाइल को पढ़ने की कोशिश कर रहे हैं, क्या आप वाकई टेक्स्ट.txt मौजूद हैं? – Dhara
आपका कोड मेरे लिए ठीक काम करता है। फाइल खोलने के ठीक बाद '' 'रिटर्न '0' बताएं, बेशक, आप और कुछ क्यों उम्मीद करेंगे? –