Data File Handling Notes
Data File Handling Notes
Data File Handling Notes
Computer Science
Class XII ( As per
CBSE Board)
File
Handling
New
Syllabus
2019-20
Once we are done working with the file, we should close the file.
Closing a file releases valuable system resources. In case we forgot to
close the file, Python automatically close the file when program ends or
file object is no longer referenced in the program. However, if our
program is large and we are reading or writing multiple files that can
take significant amount of resource on the system. If we keep opening
new files carelessly, we could run out of resources. So be a good
programmer , close the file as soon as all task are done with it.
OUTPUT
False
Name of the file is a.txt
True
f = open("a.txt", 'r')
text = f.read()
print(text)
f.close()
OUTPUT
Welcome to python.mykvs.in
Regularly visit python.mykvs.in
f = open("a.txt", 'r')
text = f.readline()
print(text)
text = f.readline()
print(text)
f.close()
OUTPUT
Welcome to python.mykvs.in
f = open("a.txt", 'r')
text = f.readlines(1)
print(text)
f.close()
OUTPUT
['Welcome to python.mykvs.in\n']
f = open("a.txt", 'w')
line1 = 'Welcome to python.mykvs.in'
f.write(line1)
line2="\nRegularly visit python.mykvs.in"
f.write(line2)
f.close()
f = open("a.txt", 'r')
for text in f.readlines():
print(text)
f.close()
f = open("a.txt", 'r')
for text in f.readlines():
for word in text.split( ):
print(word)
f.close()
OUTPUT
Welcome
to
python.mykvs.in
Regularly
visit
python.mykvs.in
Visit : python.mykvs.in for regular updates
File Handling
Append content to a File
f = open("a.txt", 'w')
line = 'Welcome to python.mykvs.in\nRegularly visit python.mykvs.in'
f.write(line)
f.close() A
P
P
E
f = open("a.txt", 'a+') N
D
f.write("\nthanks") C
f.close() O
D
E
f = open("a.txt", 'r')
text = f.read()
print(text)
f.close()
OUTPUT
Welcome to python.mykvs.in
Regularly visit python.mykvs.in
thanks