0

I have typed a program to compare vehicle A price (v_priceA) to various other vehicle prices in a carprices.txt text file which are in a new line.

The result should be a new text called highprices.txt file with all the prices greater than the price of Vehicle A in a newline and the associated line number from carprices.txt

My problem is am able to generate two text files that has the line number of the greater file and another with the greater price, instead of the greater price itself and line number together. I need to fix this.

Vehicle A price: 2500.50

v_priceA = 2500.50
a_file = 'carprices.txt'
with open(a_file, 'r') as document:
        values = [x for x, value in enumerate(document) if float(value) > v_priceA]

new_file = open('highpriceposition.txt', 'w')
for x in values:
    new_file.write(str(x) + '\n')
new_file.close()



a_file = 'carprices.txt'
with open(a_file, 'r') as document:
    values = [value for value in document if float(value) > v_priceA] 

with open('highprice.txt', 'w') as f:
    for x in values:
        f.write(str(x)+'\n')

positionprice.txt

2 2900.00
3 3500.50
5 25000.30
6 45000.50
Michael Butscher
  • 10,028
  • 4
  • 24
  • 25
lara_g1999
  • 77
  • 6

1 Answers1

0

When you write to the new file new_file.write() you need to pass it both the line number and price. I.E.

v_priceA = 2500.50
a_file = 'carprices.txt'
output_file = 'highprices.txt'


with open(a_file, 'r') as document:
    with open(output_file, 'w') as new_file:
        for line, price in enumerate(document):
            if float(price) > v_priceA:
                new_file.write(str(line) + " " + str(price))
                # See how I pass both in here?

It's important to know that whenever you open() a file in python as write "w" it's going to erase whatever is in that file before writing to it. (There's an append option if your interested). Docs for Open.

Notice how I only open the output file once in the above code? That should help.

Now on to how enumerate works. It takes an iterable object in python and for each item in that iterable returns a tuple of (itemIndex, item) with at least one very important exception it basically the succinct equivalent of:

def myEnumerate(iterableParameter):
    i = 0
    outPutList = []
    while i < len(iterableParameter):
        outPutList += (i, iterableParameter[i])
    return outPutList

The important exception is that enumerate creates a generator where as the above creates a list. See further reading.

Harry MW
  • 134
  • 1
  • 10