user7081295
user7081295

Reputation:

Extracting a user input from a text file

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

Upvotes: 0

Views: 129

Answers (1)

Laurent H.
Laurent H.

Reputation: 6526

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(...).

Upvotes: 1

Related Questions