Crappelli
Crappelli

Reputation: 3

Splitting lines in a text file into separate entries in a list?

So, I want to code a program that allows the user to do various tasks, one of which I am having some trouble with.
-Option A allows the user to search a text file by a job's 'Estimate ID', and it would search the file for that matching ID and return the relevant data in the following format:
Estimate Number: (the estimate number)
Customer ID: (the customer ID)
Estimate Amount: (the final total)
Estimate Date: (the estimate data)
Status: (the status)
 
Now, below is the format the data is stored in in the text file:
E5346,23/09/2015,C107,970,N,0
E5347,23/09/2015,C108,1050,E,0
E5348,23/09/2015,C109,370,A,200

The data is shown as Estimate Number, Estimate Date, Customer ID, Final Total (in £ pounds), Status (E for Estimate, A for Accepted Job or N for Not Accepted), and Amount Paid (in £ pounds). Obviously these are in the wrong order, and the different entries are all on one line, separated by commas, but the format cannot be changed.  
Below is the code I wrote for this:

Est_no = input ("Please enter the Estimate Number you wish to search: ")
data = []
search = open("paintingJobs.txt","r")
for line in search:
    if (Est_no) in line:
        data.append (line)
        print ("Estimate Number:",data[0])
        print ("Customer ID:", data[2])
        print ("Estimate amount:",data[3])
        print ("Estimate Date:",data[1])
        if data[4] == "E":
            status = ("Estimate")
        if data[4] == "A":
            status = ("Accepted Job")
        if data[4] == "N":
            status = ("Not Accepted")
        print ("Status:",status)
search.close()

I had what I thought was the great idea of putting the line into a list, and, as the entries are separated by commas, they would be independent entries in the list, and would print as required, but, it adds the line from the file as one entry; when I print the 1st entry in the list, which I want to be the Estimate Number, it prints the whole line, so I obviously need to split it into the separate entries I want. My question is, how?

Upvotes: 0

Views: 1439

Answers (1)

EvilTak
EvilTak

Reputation: 7579

Use string.split() to split the string by a delimiter (in this case, the delimiter is ",").

Your code under the if block will now be as follows:

# Remove the data variable definition above the for loop
if (Est_no) in line:
    data = line.split(',')
    # Process data like a list like you are already doing

Upvotes: 1

Related Questions