Notes
Notes
Method Description
This method is used to open the file for the specified operation. The
open(file_path,operation)
operation can either be r,w,a for read, write and append.
close() This method is used to close a file which is already open.
This method is used to write a string to a file, if file is present. If not,
write()
it creates the file and writes the string into it.
read() This method is used to read all the contents of a file into a string.
When we want to write a code that will run in all situations, we can put it in a finally block.
Since closing a file is necessary we can do it in the finally block instead of in the try block.
Firstly, copy "Code 1" to TryOut.py in Eclipse Plug-in. Execute and observe the results.
Code 1: Code 2:
try: hello_file=open("flight.txt"," try: hello_file=open("flight.txt","
w") text="Hello everyone! w") text="Hello everyone!
Welcome" hello_file.write(text)exce Welcome" hello_file.write(text)exce
pt: print("Error occurred, not able
to write to pt: print("Error occurred, not able
file")finally: hello_file.close()tr to write to
y: hello_file=open("flights.txt","r file")finally: hello_file.close()tr
") text_from_file=hello_file.read() y: hello_file=open("flight.txt","r"
print(text_from_file)except: pri ) text_from_file=hello_file.read()
nt("Error Occurred, not able to read print(text_from_file)except: prin
from t("Error Occurred, not able to read
file")finally: hello_file.close() from
file")finally: hello_file.close()
Q1 of 6outlined_flag
What will be the value of the variables total and game_points_history, after executing the below
code?
def check_loss(game_history,game_points,total):
if game_history[1] == 0:
game_points[1] -= 1
else:
loss_points = game_history[1] * 2
game_points[1] -= loss_points
0, [12, -4, 2]
9, [12, -5, 2]
0, [12, -9, 2]
5, [12, -9, 2]
Q2 of 6outlined_flag
Q3 of 6outlined_flag
None
0.0
6.0
Q4 of 6outlined_flag
print(func("Apple","A"),end=" ")
print(func("Apple","B"),end=" ")
print(func("Apple"),end=" ")
print(func("Apple","C"),end=" ")
4345
3235
Q5 of 6outlined_flag
Choose the statements which are CORRECT with respect to the below code
1,2,3,5
4,5,7
1,2,3,6
Q6 of 6outlined_flag
res = None
sample = ["A","B","C","D"]
values = [1,1,3,4,5]
index = func(sample,res,"B",2)
print(values[index], res)
1 None
2 None
1 True
2 True