Reputation: 21
So how can I manipulate a piece of code so that it reads from a .txt file and prints the data in a table format with headings such as 'Resident Number' 'Rent date' 'Price' etc.? The name of the file is Residents.txt
So far, I have this
file = open('Residents.txt','r')
For line in file:
SplitFile = line.split (',')
This is the .txt file-
R1,21/09/2015,C1,440,P,0
R2,21/09/2015,C3,290,A,290
R3,21/09/2015,C4,730,N,0
R4,22/09/2015,C5,180,A,180
R5,22/09/2015,C6,815,A,400
R6,23/09/2015,C7,970,N,0
R7,23/09/2015,C8,1050,P,0
R8,23/09/2015,C9,370,A,200
R9,25/09/2015,C10,480,A,250
R10,25/09/2015,C11,330,A,330
This is the representation of each column in the .txt file-
line.split[0] = Resident Number
line.split[1] = Rent Date
line.split[2] = Customer number
line.split[3] = Rent amount
line.split[4] = (A means Accepted)(N means not accepted)(P means Pending)
line.split[5] = Amount paid
PLEASE NOTE-
if amount paid equals to rent amount, that residents data shouldn't be shown in the table
if status is N or P, that residents data should also not be shown in the table
How can I display a table (WITHOUT importing modules) which has headings of 'Resident number' 'Rent date' 'Customer number' 'Rent amount' 'Amount outstanding'- amount outstanding is just rent amount - amount paid from that line. Also, how can I print a ultimate total of the outstanding amount of money (combined total for everyone that is yet to pay with a status of 'A')
Python 3.5
Thanks
EDIT
for i, word in enumerate(line):
if i == 4 : # We don't print the status
continue
elif i == 2:
continue
print(word.ljust(len(headers[i - (i > 4)(i > 2)])), end=" " * ((i - (i > 4)(i > 2)) != len(headers) - 1))
print()
FURTHER EDIT (15/02)
line = line.strip().split(",")
subtotal = int(line[3]) - int(line[5])
line.append(str(subtotal))
if line[5] == line[3] or line[4] in ("N", "E"):
continue
total += subtotal
Upvotes: 1
Views: 2158
Reputation: 20336
You can do this:
headers = ["Resident Number", "Rent Date", "Customer number", "Rent ammount", "Ammount paid", "Outstanding Ammount"]
print(" ".join(headers))
for line in open("test.txt", "r"):
line = line.strip().split(",")
line.append(str(int(line[3]) - int(line[5])))
if line[5] == line[3] or line[4] in ("N", "P"):
continue
for i, word in enumerate(line):
if i == 4:
continue
print(word.ljust(len(headers[i - (i > 4)])), end=" " * ((i - (i > 4)) != len(headers) - 1))
print()
Output:
Resident Number Rent Date Customer number Rent ammount Ammount paid Outstanding Ammount
R5 22/09/2015 C6 815 400 415
R8 23/09/2015 C9 370 200 170
R9 25/09/2015 C10 480 250 230
Upvotes: -1
Reputation: 8066
You may use tabulate
https://pypi.python.org/pypi/tabulate
from the link:
from tabulate import tabulate
table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
["Moon",1737,73.5],["Mars",3390,641.85]]
print tabulate(table)
output:
----- ------ -------------
Sun 696000 1.9891e+09
Earth 6371 5973.6
Moon 1737 73.5
Mars 3390 641.85
----- ------ -------------
Upvotes: -1