5 Python Files
5 Python Files
f = open("demofile.txt")
print(f.read())
f = open("D:\\welcome.txt")
print(f.read())
f = open("demofile.txt", "r")
print(f.readlines())
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Note: You should always close your files, in some cases, due to
buffering, changes made to a file may not show until you close the file.
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Prof. Jincy Kuriakose, Dept. of Information Technology, GEC
Idukki
Example
#Try to open and write to a file that is not writable:
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
#The program can continue, without leaving the file object open.
Prof. Jincy Kuriakose, Dept. of Information Technology, GEC
Idukki
Raise an exception
• As a Python developer you can choose to throw an exception if a
condition occurs.
• To throw (or raise) an exception, use the raise keyword.
if x < 0:
raise Exception("Sorry, no numbers below zero")