MaxyArthes MaxyArthes - 21 days ago 6
Python Question

read a file line by line and print only after its done

So I am working on doing a "simple" task since like 2h and still can't find the solution, so where is my question :
I want to search in a file, line by line, and if no result is found, at the end print something, else call a function.

def DeletItemCheckUp():
import re
find = True
itemNumber = input("\n what is the item you want to delet : ")
fileItem = open('Data_Item', 'r', encoding='Utf-8')
for line in fileItem:
sr = re.search(r'^\b%s\b'%itemNumber,(line.split(';')[0]))
if (sr == None):
pass
print("This item don't exist.")
fileItem.close()
if (find == True):
return itemNumber
DeletItem()


so here is the problem I have got with different try :
1. Print "This item don't exist." for every line that didn't had my itemNumber.
2. When there was actually no match found, its would not call DeletItem().

objectif of the code :
Ask for a item to delet, check in a file if the unique item number exist, if so, call DeletItem() to delet it, else, tell the user that this unique item number don't exist.

sal sal
Answer

Few overlooks in there to achieve what you ask. We are going to use a flag (true/false) to know when we found something, and based on that we will decide whether to call the function or print/return the number.

def DeletItemCheckUp():
    import re
    find = False      # initialize to False
    itemNumber = input("\n what is the item you want to delet : ")
    fileItem = open('Data_Item', 'r', encoding='Utf-8')
    for line in fileItem:
        sr = re.search(r'^\b%s\b'%itemNumber,(line.split(';')[0]))
        if (sr == None):
            continue  # do nothing and continue
        else:
            # we found the number, set the flag and break
            find = True
            break  # no need to continue searching
    fileItem.close()
    if (find):
        DeletItem()           # call the function
    else:
        print("This item don't exist.")
Comments