Category: Uncategorized
♤♧Working with files in Python ♧♤
Sometime, we have to work the file in python. For this purpose we use different file operations. The File operations are:-
● Read a file(“r”)
● Write a file(“w”)
● Append a file(“a”)
● Create a file(“x”)
The file operation are happening with help of open() function . Open function return a object.
■ Read the file ■
file.py
1)file_o=open("tesla.py","r")
2)with open("tesla.py")
as file_o:
con = file_o.read()
print(con)
This code open the tesla.py file and read the file.
We have to close the file properly. Because, it can lose some data. We use:
3)file_o.close()
Example,
pi_digits.py
3.1434756892380537685783
Open this file and read the content.
file_reader.py
# store the file name
file_o = "pi_digits.py"
with open("pi_digits.py") as
file_o:
con = file_o.read()
print(con)
Output ■■
3.1434756892380537685783
https://emailer.internshala.com/link.php?M=7491411&N=2823&L=449&F=H
F♨️n🌜ti🎡n return a di🌜t💈onary !🙂🙂
Suppose , we have to add additional information about user. So,how can we add a additional information when we need? With help of optional argument which has default value string. We will return a dictionary which come additional information about a user.
# creating a function
def build_person(fname,lname,
age=” ):
“”” Return a information
about a person “””
# storing dictionary in a variable
person ={
“first “:fname,
“last”:lname ,
}
# using if condition
# if this condition is true then
# age key add to dictionary.
if age:
person[“age”] = age
return person
>>>musicians = build_person(“vipul”,”kunwar”,19)
>>>print(musicians)
Output:{“first”:”vipul “,”last “:“kunwar “,age:19}

😊😊😊😊🎸🎸!
Flag in python.
Suppose there are many condition to check in a game. The conditions which stops the game. So we can do with while loop. But it becomes complex for while loop. so, python uses flag . Flag check if current position is true and many condition are true in game . So, python gives that program is active . Basically flag represent the all condition result.
prompt = "\nplease
enter the
message: "
prompt+="\nplease
tell me
something
about you: "
# game is currently
# active
active = True
while active:
a = input(prompt)
if a == "quit":
active = False
else:
print(a)
Output:
please enter the message:
please tell me something
about you:vipul
vipul
please enter the message:
please tell me something
about you:aman
aman
please enter the message:
please tell me something
about you:quit
# The player quit
# the game.
What is a flag in python while loops? – Stack Overflow
“What is a flag in python while loops? – Stack Overflow” https://stackoverflow.com/questions/59120347/what-is-a-flag-in-python-while-loops#:~:text=A%20flag%20in%20Python%20acts,of%20event%20makes%20it%20False.