Creating New File info.txt on Disk and Write New Contents to the File In Python
filepath="C:\\Users\\Admin\\Desktop\\Python
Notes\\info.txt"
#file is opened in write
mode
with open(filepath,'w')
as f:
file=f.write("India is my
country\n"
"All Indians are my
brothers and sisters.\n"
"I love my country and i
am proud if its rich varied heritage.")
# Open same file in read
mode to check file contents
print("Use of read()
function")
print("----------------------------")
with open(filepath,'r')
as f:
contents=f.read()
print("All the
contents from file are:\n",contents)
print("--------------------------------------")
print("Use of
readlines() to print particular line from file:")
with open(filepath,'r')
as f:
contents=f.readlines()
line=contents[0] # [0] it 0th index used to read first line
print("The first
line from file is:\n",line)
Output:
Use of read() function
----------------------------
All the contents from
file are:
India is my country
All Indians are my
brothers and sisters.
I love my country and i
am proud if its rich varied heritage.
--------------------------------------
Use of readlines() to
print particular line from file:
The first line from file
is:
India is my country
0 टिप्पण्या
कृपया तुमच्या प्रियजनांना लेख शेअर करा आणि तुमचा अभिप्राय जरूर नोंदवा. 🙏 🙏