Python for-loop and files

In last chapter  I explained about how you can use for-lop to create loop and use it on lists. In this chapter I will explain “Python for-loop and files” how we can use for-loop to read and write in files. Most of the time we sue for-loop only to read files. Reason is for-loop read one line in file at a time. You will understand it better with this script:

linenumber = 0
file = open("sample.txt")
for line in file:
    linenumber += 1
    print ("line number %s is --> %s " % (linenumber, line))

I don’t think I have to explain what does line number 4 do (linenumber = +1). You can check my previous post for this.


Now run this script and check the output:

Software to read and store Data

Now I am going to create another script which is bit advance, but we are using knowledge which we have seen in previous chapters. This is a big code try to understand, if you have any doubt you can ask question in comment box. But before that you need to create a sample.txt file as:


Name: Akar Periwal
Age: 26
Name: Shreya
Age: 23
Name: Vicky
Age: 25

Now Script:

def insertv():
    ex = "noexit"
    print ("Enter Name as exit to stop")
    name_file = open("sample.txt", "a")
    for i in range(1,1000):
        n = input("Enter Name: ")
        if n == "exit":
        a = input("Enter Age: ")
        name_file.write("\n\nName: %s\nAge: %s" % (n,a))
def printall():
    name_file = open("sample.txt")
    for line in name_file:
def searchname():
    name_file = open("sample.txt")
    N = []
    A = []
    for line in name_file:
        if "Name" in line:
            if "Age" in line:
    search = input("Enter 1 to search by Name\nEnter 2 to search by Age\n>")
    if search == "1":
        searchn = input("Enter Name to Search: ")
        for i in range(len(N)):
            if searchn in N[i]:
                print ("Match found with age %s" % (A[i]))
        if search == "2":
            searchn = input("Enter Age to Search: ")
            for i in range(len(A)):
                if searchn in A[i]:
                    print ("Match found with Name %s" % (N[i]))
            print ("Wrong Choice")
ch = input("""Press 1 to Insert values
Press 2 to Print all Values
Press 3 to search values
if ch == "1":
    if ch == "2":
        if ch == "3":
            print("Wrong Choice")

Now I want you to run this code and see the output, select all options.

Exercise of the day:

Change this script as your requirements, may be add another field with Name and Age.


no comments

Leave me comment