Skip to content Skip to sidebar Skip to footer

Python Beginner: How Can I Make Text #1 Look Like Text #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

Solution 1:

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: ')

withopen(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')

Post a Comment for "Python Beginner: How Can I Make Text #1 Look Like Text #2"