4/1/24, 4:05 PM filehandling
Read txt from file
In [27]: #Read txt file .
my_file=open("tariq.txt","r")
p=my_file.read()
print(p)
124
In [8]: #Read txt file using with .
with open("tariq.txt", "r") as myfile:
p = myfile.read()
print(p)
hello , everyone
my name is tariq ahmed
In [13]: #Read txt file using for loop.
myfile=open("tariq.txt","r")
for i in myfile:
print(i)
hello , everyone
my name is tariq ahmed
In [12]: #Read txt file using with and for loop.
with open("tariq.txt","r") as myfile:
for i in myfile:
print(i)
hello , everyone
my name is tariq ahmed
write file from txt file
In [20]: #write file and show output
myfile = open("tariq.txt", "w")
text = "HY i am learning a python course."
localhost:8888/nbconvert/html/Old Programming Concept/filehandling.ipynb?download=false 1/7
4/1/24, 4:05 PM filehandling
p = myfile.write(text)
myfile.close() # Close the file after writing
print(text) # Print the written content
HY i am learning a python course.
In [22]: #write a text in file and show output but using with.
with open("tariq.txt","w") as myfile:
txt="hi hi hi"
i=myfile.write(txt)
print(txt)
hi hi hi
Quiz: program to take input untill user not exit the program
and then those input (txt) write in txt file.
In [30]: myfile=open("asad.txt","w")
while True:
rollno=int(input("Enter a Roll No:"))
clas=input("Enter class :")
rollno=str(rollno)
myfile.write(rollno)
myfile.write(clas)
choice=input("Enter X for exit , Y for continue: ")
if choice =='x' or choice =='X':
break
print("file created...")
myfile.close()
#to show output
my_file=open("asad.txt","r")
p=my_file.read()
print("Output : ",p)
localhost:8888/nbconvert/html/Old Programming Concept/filehandling.ipynb?download=false 2/7
4/1/24, 4:05 PM filehandling
Enter a Roll No:6
Enter class :9th
Enter X for exit , Y for continue: x
file created...
Output : 69th
Quiz: same question but with spirit comma or with new line
and with integer input. program to take input untill user not
exit the program and then those input (txt) write in txt file.
In [43]: p=open("asad.txt","w")
while True:
rollno=int(input("Enter a roll no:"))
marks=int(input("Enter marks"))
convrt=str(rollno)+","+str(marks)
p.write(convrt)
choice=input("Enter X for exit , Y for continue: ")
if choice =='x' or choice =='X':
break
print("file created...")
myfile.close()
Enter a roll no:12
Enter marks44
Enter X for exit , Y for continue: x
file created...
In [45]: f=open("new.txt","w")
record=[]
for i in range(5):
name=input("Enter a number :")
record.append(name)
#comma add
#record.append(name+",")
localhost:8888/nbconvert/html/Old Programming Concept/filehandling.ipynb?download=false 3/7
4/1/24, 4:05 PM filehandling
f.writelines(record)
print("file created...")
f.close()
Enter a number :12
Enter a number :4
Enter a number :45
Enter a number :5
Enter a number :55
file created...
append
In [3]: #append
p=open("asnaf.txt","a")
txt="khan"
wt=p.write(txt)
print(txt)
khan
In [7]: my_file=open("newfile.txt","a")
while True:
n=input("Enter a name: ")
f=input("Enter father name :")
new=n+f
my_file.write(new)
choice =input("Enter X to Exit Y to Continue :")
if choice =='x' or choice =='X':
break
print("file created...")
my_file.close()
Enter a name: tariqkhan
Enter father name :kkkk
Enter X to Exit Y to Continue :x
file created...
small project
localhost:8888/nbconvert/html/Old Programming Concept/filehandling.ipynb?download=false 4/7
4/1/24, 4:05 PM filehandling
create a program to take user name , roll no , class/semester ,
and gpa and store in txt file.
data store untill user press x and then data append to the file
In [8]: #small project
# create a program to take user name , roll no , class/semester , and gpa and store in txt file.
# data store untill user press x and then data append to the file
project=open("project.txt","a")
while True:
name=input("Enter Your Name: ")
rollno=int(input("Enter Your Roll No: "))
semester=input("Enter Your current Semester: ")
Gpa=float(input("Enter your CGPa 4.0/? : "))
alldata=name+","+str(rollno)+","+semester+","+str(Gpa)+","
project.write(alldata)
choice=input("Enter X to Exit Y to Continue:")
if choice =="x" or choice =="X":
break
print("Data Sucessfully added")
project.close()
Enter Your Name: Tariq
Enter Your Roll No: 12
Enter Your current Semester: 7th
Enter your CGPa 4.0/? : 3.46
Enter X to Exit Y to Continue:x
Data Sucessfully added
In [4]: #same project but some extract clearness
#small project
# create a program to take user name , roll no , class/semester , and gpa and store in txt file.
# data store untill user press x and then data append to the file
project=open("project.txt","a")
while True:
localhost:8888/nbconvert/html/Old Programming Concept/filehandling.ipynb?download=false 5/7
4/1/24, 4:05 PM filehandling
name=input("Enter Your Name: ")
rollno=int(input("Enter Your Roll No: "))
semester=input("Enter Your current Semester: ")
Gpa=float(input("Enter your CGPa 4.0/? : "))
alldata="Student Name : "+name+","+"Student Roll NO : "+str(rollno)+","+"Student Current Semester: "+semester+","+"S
project.write(alldata)
choice=input("Enter X to Exit Y to Continue:")
if choice =="x" or choice =="X":
break
print("Data Sucessfully added......")
project.close()
Enter Your Name: Tariq Ahmed
Enter Your Roll No: 13
Enter Your current Semester: 8th
Enter your CGPa 4.0/? : 3.46
Enter X to Exit Y to Continue:y
Enter Your Name: Asnaf Ahmed
Enter Your Roll No: 20
Enter Your current Semester: 7th
Enter your CGPa 4.0/? : 3.40
Enter X to Exit Y to Continue:x
Data Sucessfully added......
In [ ]:
CSV FILE
In [2]: import csv
myfile = open("khan.csv", "a", newline="")
obj = csv.writer(myfile)
obj.writerow(["Name", "Roll No"])
data = (["tariq", "12"])
obj.writerow(data)
localhost:8888/nbconvert/html/Old Programming Concept/filehandling.ipynb?download=false 6/7
4/1/24, 4:05 PM filehandling
myfile.close()
print("Data added...")
Data added...
In [5]: # Create a function to add a contact: Define a function called add_contact() that prompts the user for contact informati
# Create a function to view contacts: Define a function called view_contacts() that reads the CSV file and displays all
import csv
def add_contact():
name=input("Name:")
email=input("Email:")
phone_number=input("Phone:")
with open("addressbook.csv","a",newline="") as book:
obj=csv.writer(book)
obj.writerow(["Name","Email","Phone"])
data=name,email,phone_number
obj.writerow(data)
book.close()
print("added")
add_contact()
def view_contacts():
with open("addressbook.csv","r") as book:
csvreader = csv.reader(book)
for row in csvreader:
print(row)
view_contacts()
Name:yasir
Email:ggg@tes.com
Phone:87867576858
added
['Name', 'Email', 'Phone']
['tariq', 'aca@gmail.com', '7897897']
['Name', 'Email', 'Phone']
['asnaf', 'test@123.com', '676757656745']
['Name', 'Email', 'Phone']
['yasir', 'ggg@tes.com', '87867576858']
localhost:8888/nbconvert/html/Old Programming Concept/filehandling.ipynb?download=false 7/7