Python file handling
Python में file handling का उपयोग कर files को create open read write व delete किया जा सकता है।
Open() function
open() function का उपयोग कर files को create, read व write कर सकते है। मुख्यता यही function पूरी file handling में उपयोग किया जाता है।
Syntax
fileobject = open(<file-name>, <access-mode>, <buffering>) Create new file
new file create करने के लिए open() function में access mode x सेट करना होता है।
fileobj = open("myfile.txt","x");
print(fileobj)
if fileobj:
print("File created successfully")Write file
file में लिखने के लिए open() function में access mode w सेट करना होता है। अगर file create नहीं हुई है तो create कर देगा। अगर फाइल में content पहले से है तो overwrite कर देगा।
fp= open("myfile.txt","w")
fp.write("Hello world how are you")
fp.close()Append file
फाइल में content पहले से है और उसमे और content ऐड करना है तब append access mode का उपयोग किया जाता है।
fp= open("myfile.txt","a")
fp.write("Hello world how are you")
fp.close()Read file
फाइल से content को रीड करने के लिए open() function में access mode r सेट करना होता है।
fp= open("myfile.txt","r")
print(f.read())
fp.close()Read first 10 characters
fp= open("myfile.txt","r")
print(f.read(10))
fp.close()Read first Line from file
fp= open("myfile.txt","r")
print(f.readline()) # read first line
fp.close()Read all lines from file
fp= open("myfile.txt","r")
for lines in fp:
print(lines)
fp.close()Close a file
files में operations perform करने के बाद फाइल को close करना बहुत ज़रूरी होता है। इसके लिए close() function का उपयोग किया जाता है।
fp = open("myfile.txt", "r")
print(fp.read())
f.close()Delete a file
Python में फाइल को delete करने के लिए os module को import करना होता है।
import os
os.remove("myfile.txt")Create Folder/Directory
os module के mkdir() function का उपयोग कर folder को create कर सकते है।
import os
os.rmdir("myfiles")Delete Folder/Directory
os module के rmdir() function का उपयोग कर folder को delete कर सकते है।
import os
os.rmdir("myfiles")File exist or not
import os
if os.path.exists("myfile.txt"):
print('file exists')
else:
print("file does not exist")

0 टिप्पणियाँ
If you have any doubt. Please let me know