0

Trying to input text file (text #1) and output to another text file (text#2) in the following format. Running into an error. I am new to Python and any help would be appreciated.

Text #1

$1120.47 $944.42
$72.29 $588.23
$371.21 $2183.84

Text #2

$ 1120.47  $  944.42  $ 2064.89
$   72.29  $  588.23  $  660.52
$  371.21  $ 2183.84  $ 2555.05

What I have so far:

inputfilename= input('Enter sales file name: ')
outputfilename=input('Enter name for total sales file: ')

with open(inputfilename, 'r') as i, open(outputfilename, 'w') as o:
    for line in i:
        fst_sale, lst_sale = line.split(' ')
        fst_sale = float(fst_sale[1:])
        lst_sale = float(lst_sale[1:])
        tot_sale = fst_sale + lst_sale
        new_line = ''.join(
            ['$' + str(x).rjust(10) 
            for x in [fst_sale, lst_sale, tot_sale]]
        )
        o.write(new_line + '\n')

I get this error when I hit run:

 fst_sale, lst_sale = line.split(' ')
ValueError: not enough values to unpack (expected 2, got 1)
  • Read and follow [How to debug small programs (#1)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) - you probably have some empty lines in front/at end of your file, which is read and cant be decomposed into 2 parts as it has no 2 parts. – Patrick Artner May 26 '18 at 21:14
  • @jpp same author, same code, other problem - no dupe. just lack of trying to solve own problems. – Patrick Artner May 26 '18 at 21:17

1 Answers1

0

The error message tells you exactly whats wrong: You try to split a line at ' ' and decompose it into 2 parts but only got 1 part. Sensible thing to do would be to set a breakpoint and inspect the line - or uncomment the splitting and instead print it, to inspect it.

You can avoid that error by testing if your line contains 2 parts before actually decomposing it into 2 parts:

with open(inputfilename, 'r') as i, open(outputfilename, 'w') as o:
    for line in i:
        if len(line.split(" ")) == 2: # only do it if you can split in 2 parts 
            fst_sale, lst_sale = line.split(' ')
            fst_sale = float(fst_sale[1:])
            lst_sale = float(lst_sale[1:])
            tot_sale = fst_sale + lst_sale
            new_line = ''.join(
                ['$' + str(x).rjust(10) 
                for x in [fst_sale, lst_sale, tot_sale]]
            )
            o.write(new_line + '\n')

Read and follow How to debug small programs (#1) - it will enable you to solve your own problems.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69