We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 3
Files and Exceptions
In this lab session, you are going to learn;
Types of files and file access methods
Filenames and file objects
Writing data to a fi
Reading data from a file and determining when the end of the file is reached
Processing records
Exceptions, including:
"Traceback messages
"Handling exceptions
o00000
1) Consider following statements and see the results.
Mode "w" means that we are opening # the file for writing
= open("test.txt","w")
print(#)
# To put data in the file we invoke the write method on the file object
F.write("Now is the time")
f.urite(" to close the fil
)
# Closing the file makes the file available for reading:
F.close()
2) Open the file in Example 1 again, this time for reading, and read the contents into a string.
See the results,
£ = open("test.txt","r")
text = f.read()
print (text)
expected result in console: Now is the time to close the file
F = open(“test. txt"
print(f.read(5))
expected result in console: Now i
ane")
# we are able to return remaining characters
print (f.read(10@0086) )
expected result in console: s the timeto close the file3) Consider following example about file positions and see the results.
# Open a file
fo = open("foo.txt", “w")
fo.write("Python is a great language.\nYeah its great!!\n")
# Open file again with different mode
fo = open("foo.txt", "r+")
str = fo.read(17);
print(“Our String is : ", str)
# Check current position
position = fo.tell();
print("Current file position : “, position)
# Reposition pointer at the beginning once again
position = fo.seek(@, 0);
str = fo.read(17);
print(“Again Our String is : ", str)
# Close file
fo.close()
4) See the following example about exceptions and see the results.
# This example tries to open a file where you do not have write permission, so it
# raises an exception
try:
‘fh = open("testfile", "r")
fh.write("This is my test file for exception handling!")
except T0Error:
print("Error: can\'t find file or read data")
else:
print("Written content in the file successfully")# Example 2 with finally clause (If you do not have permission to open the file in
# uniting mode, output is following)
try
fh = open(“testfile”, “w")
Fhwnite("This is ay test file for exception handling!")
finally:
print “Error: can\'t find file or read data”