Reputation: 123
I want to read ONLY the fourth and fifth column of this text file
sample.txt
2012-01-01 09:00 San Jose Men's Clothing 214.05 Amex
2012-01-01 09:00 Fort Worth Women's Clothing 153.57 Visa
2012-01-01 09:00 San Diego Music 66.08 Cash
I am able to do this, but the format of the output isn't what I want.
output
Men's Clothing 214.05
Women's Clothing 153.57
Music 66.08
Desired output
Men's Clothing 214.05
Women's Clothing 153.57
Music 66.08
Here is my code (I used some formatting but it's still not giving me the desired output):
for line in open("sample.txt"):
strsales=line.split()[-2]
item=line.split('\t')[3]
itemsales=item+"{0:>33}".format(strsales)
print(itemsales)
Upvotes: 1
Views: 7393
Reputation: 16951
This line:
itemsales=item+"{0:>33}".format(strsales)
is padding out the number to 33 positions. But the length of item
is variable, and that is causing your alignment to go out. Look closely and you will see that the unevenness in row 1 and row 2 is 2 positions, and that is exactly the difference in length between Men's Clothing
and Women's Clothing
. You need to pad out both variables to a constant number of positions. Try this
itemsales = "{0:<33}{1:>18}".format(item,strsales)
Upvotes: 3