0

I have a text file that is called paintingJobs.txt, each line is structured in this way:

Estimate Number, Estimate Date, Customer ID, Final Total, Status (E for Estimate, A for Accepted job or N for Not accepted), and Amount Paid. Here is an extract:

E5341, 21/09/2015, C102, 440, E, 0

E5342, 21/09/2015, C103, 290, A, 290

E5343, 21/09/2015, C104, 730, N, 0

I would like the user to input any Estimate number and for that line to be outputted. How can I achieve this?

Here is what I came up with but it doesn't work as required:

def option_A():
    es_num = str.upper (input ("Please enter the estimate number: "))
    with open('paintingJobs.txt', 'r') as file:
        line = file.readline ()
        print (line, end = '')
        if es_num in file:
            #print whole line 

        else:
             print("Not found")

I would like to display the information in this format

Estimate Number: the estimate number

Customer ID: the customer ID

Estimate Amount: the final total

Estimate Date: the estimate date

Status: the status

1 Answer 1

1

To print the line, I suggest you to simply iterate on each line of the file as follows:

def option_A():
    es_num = str.upper (input ("Please enter the estimate number: "))
    result = "Not found"
    with open('paintingJobs.txt', 'r') as file:
        for line in file:
            if es_num in line:
                result = line
                break
    print(result)

To format the display, you can split the line with comma as separator to get a list of information. Then format your display, as follows:

data = result.split(',')
print("Estimated number:{0}".format(data[0]))
print("Customer ID:{0}".format(data[2]))
...etc...

Then if you need some data which are more complex to retrieve from the text file, the powerful way is to use regex with for instance the method re.match(...).

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your help. I have a question why have you used the break outside a while loop?
I used the break to stop the "for" loop at first match. Reading your post I assumed that only one line can match the user input. Am I right ?
so you can use 'break' to stop any type of loop?
Yes. In order to format the displayed information, you should use result.split(',') to split the line into a list of information of the line (using comma as separator).
Thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.