2

I am trying to create a loop that will format, space, and align the 1st text to match the 2nd text. I am inputting text 1 from a txt file and I want it to output text 2 into a txt file. The syntax should print text #2 with the 3rd column summed.

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

This is what I have so far...you can tell this is only my 2nd week writing python.:) Any help would be appreciated.

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

infile=open(inputfilename, "r")
outfile=open(outputfilename, "w")

salessequence=infile.readlines()

for sale in salessequence:
    splitsale=sale.strip().split(" ")
    firstsale=splitsale[0]
    lastsale=splitsale[1]
    dollarsign1=firstsale[0:1]
    firstsale2=firstsale[1:]
    lastsale2=lastsale[1:]
    total=firstsale2 + lastsale2
    print(total, file=outfile)

infile.close()
outfile.close()

print('All finished')
KiteCoder
  • 2,364
  • 1
  • 13
  • 29

1 Answers1

0

Three things to correct in your attempt:

  1. Use the string method rjust (right-justify) to align columns. It adds extra spaces to the start of a string.

  2. Always close a file after reading writing is complete. Alternatively use the with syntax (see code example below) as it automatically closes the file after exiting the with block.

  3. Use file.write to write lines to a file

  4. look at the csv module & pandas library as they provide advanced data & file handling techniques.

example code to read from a file & write to a new file:

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')
Haleemur Ali
  • 26,718
  • 5
  • 61
  • 85
  • Thank you, this was very helpful! One question, when I try to run the example code I get this error. fst_sale, lst_sale = line.split(' ') ValueError: not enough values to unpack (expected 2, got 1) –  May 26 '18 at 18:30
  • What is the best way to resolve the following error? fst_sale, lst_sale = line.split(' ') ValueError: not enough values to unpack (expected 2, got 1) –  May 26 '18 at 18:31
  • that error means that your file has a line that doesn't have a space. try `'abc def'.split(' ')`. it should output `['abc', 'def']`. now try 'abcdef'.split(' ') in the console. this will output `['abcdef']` – Haleemur Ali May 26 '18 at 18:33