Python – File Handling
Python मे भी अन्य programming language की तरह file handling का concept है । लेकिन पाइथन मे फाइल हैंडलिंग का concept बहुत short और easy है ।
पाइथन user को file handling के लिए allow करता है और पाइथन यूजर को फाइल read और write करने के साथ साथ अन्य file handling options प्रदान करता है । पायथन फाइल को text या binary के रूप में अलग तरह से treat है |
Access Mode to Open a File
"r"
– Read – Open a file to read only , this is Default mode
"a"
– Append – Open a file is append mode
"w"
– Write – Open a file for write only
"rb"
– Open a file to read only in binary format .
"r+"
– Open a file to read and write
"rb+"
– Open a file to read and write in binary format .
"wb"
– Open a file to write only in binary format .
"wb+"
– Open a file to read and write in binary format .
"ab"
– Open a file is append mode in binary format .
Python - Data types
The Open ( ) method
python मे फाइल को open करने के लिए पाइथन open ( ) method provide करता है ।
open ( ) method मे दो arguments (file name और access mode ) pass किये जाते है जिससे हम फाइल को एक्सेस कर सकते है ।
Syntax :
file object = open(<file-name>, <access-mode>, <buffering>)
Example :
# opens the file IO.txt in read mode
f = open("IO.txt", "r")
print("file is opened successfully")
# output
file is opened successfully
The close ( ) method
पाइथन मे जब किसी फाइल को open करके उसमे operations को पूरा कर लिया जाता है तो फाइल को close करना पड़ता है । फाइल को close करने के लिए close ( ) method का उपयोग किया जाता है ।
Syntax :
fileobject.close()
Example :
# opens the file IO.txt in read mode
f = open("IO.txt", "r")
print("file is opened successfully")
#closes the opened file
f.close()
Reading the File
पाइथन मे किसी file को read करने के लिए read ( ) method का use किया जाता है । read ( ) मेथड के दवारा फाइल से string को रीड किया जाता है ।
syntax :-
fileobject.read(<count>)
Example :-
# open the IO.txt file in read mode.
f = open("IO.txt", "r");
# stores all the data of the file into the variable content
content = f.read();
# prints the type of the data stored in the file
print(type(content))
# prints
print(content)
# close the open file
f.close()
# output
<class 'str'>
welcome ! thetechnicalnotes.com