why is the formatting not identical between what is displayed when I execute my
ID: 3850166 • Letter: W
Question
why is the formatting not identical between what is displayed when I execute my code in visual studios and it displays on the console versus what is displayed in the output.txt file? why is the ' ' showing up in the output.text file and why aren't the ID's listed line by line instead of merging together having two different people on the same line at times?
my code is as follows and the above is what I get:
f = open("C:\Usersuser\Desktop\payroll.txt", "r")
outfile = open('C:\Usersuser\Desktop\output.txt','w')
output=[]
for line in f.readlines():
columns=line.split()
id=columns[0]
name=columns[1] + ' ' + columns[2]
wage=float(columns[3])
days=columns[4:]
totalhours=0
for hour in days:
totalhours=totalhours + float(hour)
averageHours=totalhours/len(days)
totalPay=totalhours*wage
result=name+' ID'+id+' worked '+str(totalhours)+' hourly pay $'+str(wage)+' hours: ' + str(averageHours) + '/day Total Pay: $' + str(totalPay)
print(result)
output.append(result+' ')
outfile.write(output.__str__() + ' ')
outfile.close()
Explanation / Answer
1. The issue is with writing list as string to output file.
2. Variable output is of list type, each item is a line of text.
3. Re-write the code such that it iterates over list output and add each line to output file.
__________________________________________________________________________________________
Updated Code:
f = open("C:\Usersuser\Desktop\payroll.txt", "r")
outfile = open('C:\Usersuser\Desktop\output.txt','w')
output=[]
for line in f.readlines():
columns=line.split()
id=columns[0]
name=columns[1] + ' ' + columns[2]
wage=float(columns[3])
days=columns[4:]
totalhours=0
for hour in days:
totalhours=totalhours + float(hour)
averageHours=totalhours/len(days)
totalPay=totalhours*wage
result=name+' ID'+id+' worked '+str(totalhours)+' hourly pay $'+str(wage)+' hours: ' + str(averageHours) + '/day Total Pay: $' + str(totalPay)
print(result)
output.append(result+' ')
# Iterating over each item in list variable
for line in output:
# Writing each line to output file
outfile.write(line)
# Closing output file
outfile.close()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.