Luciana Zabini
Luciana Zabini

Reputation: 11

Opening two files, processing the first and pasting it to the second

I'm trying to take one file, change the formatting and some other stuff, then put the changes into a second file.

The inputfile.txt looks like this:

item: 8.00

item2: 9.00

item3: 8.55

def thisisthefunction():
    infile = open('inputfile.txt')
    outfile = open('outputfile.txt', 'w')
    total = 0
    while True:
        contents = infile.readline()
        if ("" == contents):
            break;
        if ":" in contents:
            contentlist = contents.split(':')
            price = float(contentlist[1])
            outfile.write('{:30}{:8.2f}'.format(contentlist[0], price))
            total = total + price

    outfile.write('{:30}{:8.2f}'.format('Total:', total))
    infile.close()
    outfile.close()

readoutfile = open('outputfile.txt', 'r')
print(readoutfile.readline())
readoutfile.close()

I hoped to have it in rows and columns in outputfile.txt as:

item: 8.00

item2: 9.00

item3: 8.55

total: 25.55

but the actual output is:

item: 8.00item2: 9.00item3: 8.55total: 25.55

Upvotes: 0

Views: 16

Answers (1)

furas
furas

Reputation: 142681

write() unlike print() doesn't add '\n' at the end so you have to add it on your own.

outfile.write( text + "\n" )

or

outfile.write( text )
outfile.write( "\n" )

You can also add in formated text '{:30}{:8.2f}\n'

outfile.write('{:30}{:8.2f}\n'.format(contentlist[0], price))

outfile.write('{:30}{:8.2f}\n'.format('Total:', total))

Upvotes: 1

Related Questions