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
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
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
----- ------ -------------
Related
I am doing a POS machine which save the data in a text file. After customer buy item, the total quantity of the item in the text file will minus the quantity of the customer brought, but after I trying the code can works but the stock quantity in the text file remain unchanged. So, I found some answer from this SO question Reducing quantity in text file
, it works for them but mine can't. What gone I to do for my code work.
This is the contein of my text file named razershop.txt(id, name, price, quantity):
1 , Razer Deathadder V2, 349.00 , 100
2 , Razer Viper Ultimate, 419.00 , 105
3 , Razer Basilink Ulti, 599.00 , 35
4 , Razer Viper Mini, 139.00 , 295
5 , Raazer Deathadder X, 76.90 , 592
I used all_products to open my file:
all_products = [line.strip().split(',') for line in open('razershop.txt','r').readlines()]
This is the decrement item function code:
def decrement_item(item_id, quantity):
with open('razershop.txt', 'r') as fin:
# indexes for id and quantity
index_id = 0
index_quantity = 3
# output buffer
output = []
# Add headaer to output buffer
header = fin.readline().rstrip()
output.append(header) # header without '\n' at end of line
bfound_item = False
for line in fin:
# Check each line for item_id then upadte quantity
line = line.rstrip()
if not bfound_item:
# Only process if item_id has not been found yet
# Break line into separate fields
row = line.split()
current_id = row[index_id]
if current_id == item_id:
# Found item
# Check if sufficiente quantity
current_quantity = int(row[index_quantity])
if current_quantity >= quantity:
# Decrement quantity
current_quantity -= quantity
row[index_quantity] = str(current_quantity)
line = ' '.join(row)
bfound_item = True
else:
# Insufficient quantity for update
s = f"Sorry, available quantity is only {int(row[index_quantity])}"
raise Exception(s)
# Add line to output
output.append(line) # add copy since row changes with loop
# Update inventory file
with open('razershop.txt', 'w') as fout:
for line in output:
fout.write(line + '\n')
This is my Pos machine code which generate bill and will decrease the stock after customer buy it:
while(True):
banner()
choice = int(input("Please enter your option: "))
if choice == 1:
display_all()
elif choice == 2:
display_all()
print("Press 0 for payment")
item_lst = []
price_lst = []
quantity_lst = []
total_price = 0
prod_id = 999
while prod_id != 0:
prod_id = int(input("Enter the Product ID: "))
for item in all_products:
if int(item[0]) == prod_id:
quantity = int(input("Please enter the quantity: "))
item_lst.append(item[1])
quantity_lst.append(quantity)
price_q = float(item[2]) * quantity
price_lst.append(price_q)
total_price = total_price + price_q
decrement_item(prod_id , quantity)
order_summary(item_lst , price_lst , total_price , quantity_lst)
print(" ")
conf = input("Please confirm your order(Y/N): ")
if conf == "Y":
member = input("Do you have membership(Y/N): ")
if member == "Y":
total_price = total_price * 0.9
payment = float(input("Amount received: "))
change = payment - total_price
generate_bill(item, total_price, item_lst , price_lst , quantity_lst ,change , payment)
print(" ")
print("Thanks For shopping with Us :)")
sys.exit(0)
else:
payment = float(input("Amount received: "))
change = payment - total_price
generate_bill(item, total_price, item_lst , price_lst , quantity_lst ,change , payment)
print(" ")
print("Thanks For shopping with Us :)")
sys.exit(0)
else:
print("Continue Exploring the shop")
Output:
Upper output for customer to enter the item they want
Below part of the output which generate bill
(Sorry guys the output I can't put it in image form becuase SO not allow me so they changed my image to a link)
I had tried delete the with open('razershop.txt', 'r') as fin: and header = fin.readline().rstrip() and ( row = line.split() and change all the row variable to line fromfor line in fin: # Check each line for item_id then upadte quantity line = line.rstrip()from the decrement_item function. It end up with a infinity loop and last time I forgot what I had done with the code from the decrement_ item function the whole text in the txt file gone. I just want to know what should I do to make this work?
i can only use one loop, one if statement and i used my only if statement to filter the rows in a csv file to print specific rows with the same job name. so i used a try except to find the average of the salary income.
to give values inside the for loop i used sum() to fill up the total_salaries but because the salaries were in float it didn't work. here is the code:
for line in reader:
name, job, salary = line
salary = float(salary)
salary = salary + (salary*0.1)
instructor_count = len(line)
total_salaries = sum(salary)
i tried writing total_salaries = sum(float, salary) but that gave me a type error
here is the full code to get the complete picture:
import csv
file = open('SP21-Emp1.txt', 'r')
reader = csv.reader(file)
total_salaries = 0
instructor_count = 0
print("Reading from file SP21-Emp1.txt" "\n")
for line in reader:
name, job, salary = line
salary = float(salary)
salary = salary + (salary*0.1)
instructor_count += 1
total_salaries += salary
if job == 'Instructor':
instructor_count += 1
total_salaries += salary
first_name, last_name = name.split(' ', 1)
print(f'Name: {last_name} {first_name} \t Job: {job} \t Income: {salary}',)
try:
average_instructor_salary = total_salaries / instructor_count
except ValueError:
print('can not calculate average because there were no instructor salaries found.')
average_instructor_salary = "No instructor salary found"
my output was this:
Reading from file SP21-Emp1.txt
Name: Tweijari Bilal Job: Instructor Income: 2200.0
Name: Hachem Nizar Job: Instructor Income: 1980.0
Name: Saeed Walaa Job: Instructor Income: 2090.0
Name: Khattar Nadine Job: Instructor Income: 1628.0
The average of the instructors' salaries is: 1493.8
but if you look at the average for my output and the expected output that is coming up you will see that it is different.
Reading from file SP21-Emp1.txt
Name: Tweijari, Bilal Job: Instructor Income: $2200.0
Name: Hachem, Nizar Job: Instructor Income: $1980.0
Name: Saeed, Walaa Job: Instructor Income: $2090.0
Name: Khattar, Nadine Job: Instructor Income: $1628.0
The average of the instructors' salaries is: 1974.5
this is the latest update, i am a certified dumbass, i copyed and pasted the print line in the wrong place... so now i do get a value but it is still not the expected value
import csv
file = open('SP21-Emp1.txt', 'r')
reader = csv.reader(file)
total_salaries = 0
instructor_count = 0
print("Reading from file SP21-Emp1.txt" "\n")
for line in reader:
name, job, salary = line
salary = float(salary)
salary = salary + (salary*0.1)
instructor_count += 1
total_salaries += salary
if job == 'Instructor':
first_name, last_name = name.split(' ', 1)
print(f'Name: {last_name} {first_name} \t Job: {job} \t Income: {salary}',)
try:
average_instructor_salary = total_salaries / instructor_count
print("\n" "The average of the instructors' salaries is:", average_instructor_salary)
except ValueError:
print('can not calculate average because there were no instructor salaries found.')
average_instructor_salary = "No instructor salary found"
salary is not a list of elements. so sum(salary) will not give a total sum. you can try total_salaries += salary
Here's the code I'm running, which is an exact copy of your code:
import csv
file = open('SP21-Emp1.txt', 'r')
reader = csv.reader(file)
total_salaries = 0
instructor_count = 0
print("Reading from file SP21-Emp1.txt" "\n")
for line in reader:
name, job, salary = line
salary = float(salary)
salary = salary + (salary*0.1)
instructor_count += 1
total_salaries += salary
if job == 'Instructor':
first_name, last_name = name.split(' ', 1)
print(f'Name: {last_name} {first_name} \t Job: {job} \t Income: {salary}',)
try:
average_instructor_salary = total_salaries / instructor_count
print("\n" "The average of the instructors' salaries is:", average_instructor_salary)
except ValueError:
print('can not calculate average because there were no instructor salaries found.')
average_instructor_salary = "No instructor salary found"
Here is the CSV file I used:
C:\tmp>cat SP21-Emp1.txt
Tweijari Bilal,Instructor,2000
Hachem Nizar,Instructor,1800
Saeed Walaa,Instructor,1900
Khattar Nadine,Instructor,1480
C:\tmp>
Here is the output I receive:
C:\tmp>python x.py
Reading from file SP21-Emp1.txt
Name: Bilal Tweijari Job: Instructor Income: 2200.0
Name: Nizar Hachem Job: Instructor Income: 1980.0
Name: Walaa Saeed Job: Instructor Income: 2090.0
Name: Nadine Khattar Job: Instructor Income: 1628.0
The average of the instructors' salaries is: 1974.5
I am taking a course through school and have this challenge on Codio:
For your final challenge in this unit, you will load two files:
The first file F1 will have information about some accounts. It will be pipe-delimited and have one record per line, with these fields:
ACCOUNT NUMBER | PIN CODE | BALANCE
The second file F2 will contain instructions: one on each line. The instructions will look like this:
COMMAND | AMOUNT | ACCOUNT NUMBER | PIN CODE
COMMAND will be either add or sub. If the command is add, you will add AMOUNT to the BALANCE in the account files F1. If the command is sub, you will subtract.
However, there are a number of reasons for which you may need to reject the transaction. If you are asked to subtract an amount that would put the account below zero or if the pin code you are provided does not match the pin code in the account record, the transaction is ignored.
Account Transactions
Given pipe-delimited files F1 and F2 where F1 contains accounts with fields ACCOUNT NUM|PIN|BALANCE and F2 contains transaction instructions COMMAND|AMOUNT|ACCOUNT NUM|PIN, execute the transactions, storing the results back in F1.
The COMMAND field will be add or sub indicating addition or subtraction from the account.
Transactions which do not provide the correct PIN code or attempt to put the account below zero should be ignored.
This is my code for the challenge:
records = []
with open(F1,'r') as account_info:
content = account_info.readlines()
for row in content:
recordList = row.strip("\n").split('|')
records.append(recordList)
records2 = []
with open(F2,'r') as user_input:
content2 = user_input.readlines()
for row in content2:
recordList2 = row.strip("\n").split('|')
records2.append(recordList2)
for i in range(len(records)):
row = records[i]
for i in range(len(records2)):
row = records2[i]
for row in records and records2:
if records[i][1] == records2[i][3] and records2[i][0] == "add":
newBalance = int(records[i][2]) + int(records2[i][1])
records[i][2] = str(newBalance)
elif records2[i][0] == "sub" and int(records[i][2]) >= int(records2[i][1]):
newBalance = int(records[i][2]) - int(records2[i][1])
records[i][2] = str(newBalance)
output_records = ""
i = 0
while i <= len(records):
output_records += '|'.join(records[i])
if i != len(records):
output_records += '\n'
i += 1
if i == len(records):
break
outputFile = open(F1, 'w')
outputFile.write(output_records)
outputFile.close
This is what I'm getting for output which is off by one number.
Your program output did not match the expected output.
Your output:
1000|1234|10000
1020|2222|0
3000|3344|0
2020|1234|90000
Expected output:
1000|1234|11000
1020|2222|0
3000|3344|0
2020|1234|90000
Can someone point me in the direction of where I'm going wrong? Thanks.
Assume amount and balance are integer-valued.
For float change int(...) to float(...) in Code
Code
# Get Records
with open('file1.txt','r') as f1:
records = []
for row in f1:
row = row.rstrip().split('|')
# Strip white space and convert balance to float
row = [x.strip() if i != 2 else int(x.strip()) for i, x in enumerate(row)]
records.append(row)
# Get Transactions
with open('file2.txt', 'r') as f2:
transactions = []
for row in f2:
row = row.rstrip().split('|')
# Strip whitespace and convert balance to float
row = [x.strip() if i != 1 else int(x.strip()) for i, x in enumerate(row)]
transactions.append(row)
# Perform Transactions
for t in transactions:
for record in records:
# check records for matching account & pin
# Brute force search -- okay for records and transactions only in thousands
if t[2:] == record[:2]:
# Found account to update (record account & pin matches transaction)
if t[0] =='add':
record[-1] += t[1] # increment balance
elif t[0] == 'sub':
if record[-1] - t[1] >= 0:
record[-1] -= t[1] # decrement balance
break
# Output updated records
with open('file1.txt', 'w') as f3:
for row in records:
row = [str(x) for x in row]
f3.write(' | '.join(row) + '\n')
Test
Prior to running
File1.txt
1000 | 1234 | 10000
1020 | 2222 | 2500
3000 | 3344 | 3000
2020 | 1234 | 95000
File2.txt
add | 1000 | 1000 | 1234
sub | 1000 | 1020 | 2222
add | 1000 | 3000 | 3344
sub | 1000 | 2020 | 1234
After running
File1.txt
1000 | 1234 | 11000
1020 | 2222 | 1500
3000 | 3344 | 4000
2020 | 1234 | 94000
I think the problem could come from these:
for row in records and records2:
if records[i][1] == records2[i][3] and records2[i][0] == "add":
newBalance = int(records[i][2]) + int(records2[i][1])
records[i][2] = str(newBalance)
elif records2[i][0] == "sub" and int(records[i][2]) >= int(records2[i][1]):
newBalance = int(records[i][2]) - int(records2[i][1])
records[i][2] = str(newBalance)
From what I see, if records[i][1] != records2[i][3] it still run the elif and subtract.
Your code is really messy, i can advise you to delete all and restart from an empty file:
the following lines are meaningless:
for row in records and records2:
for i in range(len(records)):
row = records[i]
for i in range(len(records2)):
row = records2[i]
If you know how to use dictionaries, they might help a bit:
Here there is some pseudo code of a possible type of solution:
accounts = {}
with open(F1,'r') as f:
for line in f:
acc, pin, balance = line.split('|')
accounts[acc] = {'pin': pin, 'balance': int(balance)}
with open(F2,'r') as f:
for line in f:
command, amount, acc, pin = line.split('|')
amount = int(amount)
if accounts[acc]['pin'] != pin:
continue # wrong pin
if command == 'add':
accounts[acc]['balance'] += amount
elif accounts[acc]['balance'] >= amount: # if there is enough balance to sub
accounts[acc]['balance'] -= amount
I'm still new to Python. I want to make a Car loan calculator that only runs in command prompt. The Calculator needs to take input from the users.
I managed to get the input of the users and print the list of prices in the CSV file. I need to find the closest price in the CSV file that is closest to my variable vehiclecost. Is there any code I can use to do that?
Code:
carlist = open("carlist.csv")
data = carlist.readline()
print("Vehicle cost:")
vehiclecost = float(input().strip("! .? % $"))
print("Annual interest rate:")
AnnualInterestRate = float(input().strip("! .? % $"))
print("Loan duration:")
loandur = int(input().strip("! .? % $"))
while loandur > 10:
print("Try again your loan duration is too long!")
loandur = float(input().strip("! .? % $"))
loanmonth = (loandur * 12)
carwithtax = (vehiclecost * 0.12 + vehiclecost)
InterestRate = AnnualInterestRate / (100 * 12)
monthlypayment = carwithtax * (InterestRate *
((InterestRate + 1)**loanmonth)) / ((InterestRate + 1)**loanmonth - 1)
print("Your loan amount would be: " + str(carwithtax))
print("Your monthly payment would be: {:.2f}".format(monthlypayment))
for x in range(1, loandur + 1):
for y in range(12):
monthlyinterest = (carwithtax * InterestRate)
principal = (monthlypayment - monthlyinterest)
carwithtax = float(carwithtax - principal)
print("Years:", x)
print("Bal remaining: {:.2f}".format(carwithtax))
month = x * 12
print("Total payemtns, {:.2f}".format(month * monthlypayment))
print("Car Recomendation")
for data in carlist:
price = data.split(",")
if int(price[0]) < vehiclecost:
lower = data.split(",")
print(lower)
My input file: Carlist.csv
Snippet
To find the closest value vehicle from the data set:
# get the price list from the csv
price_list = [row[0] for row in car_list]
# get the closest value vehicle
closest_value_vehicle = min(price_list, key=lambda x:abs(int(x)-vehicle_cost))
Full Code
I cleaned up the code a little and added commenting.
Tested with the supplied dataset.
import csv
with open('carlist.csv', 'r') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
# skip header
next(reader, None)
# assign car list
car_list = list(reader)
while True:
try:
# vehicle cost
vehicle_cost = float(input("Please enter the vehicle cost:").strip("! .? % $"))
except ValueError:
print("Invalid input. Vehicle cost must be numeric.")
continue
else:
break
while True:
try:
# annual interest rate
annual_interest_rate = float(input("Please enter the annual interest rate:").strip("! .? % $"))
except ValueError:
print("Invalid input. Annual interest rate must be numeric.")
continue
else:
break
while True:
try:
# loan duration
loan_duration = int(input("Please enter the loan duration:").strip("! .? % $"))
except ValueError:
print("Invalid input. Loan duration must be numeric.")
continue
if loan_duration > 10:
print("Invalid input. Loan duration must be less than 10.")
continue
else:
break
# total loan months
loan_total_months = loan_duration * 12
# vehicle tax
vehicle_tax = vehicle_cost * 0.12 + vehicle_cost
# interest rate
interest_rate = annual_interest_rate / ( 100 * 12 )
# monthly repayment
monthly_repayment = vehicle_tax * ( interest_rate * ( ( interest_rate + 1 ) ** loan_total_months ) ) / ( ( interest_rate + 1 ) ** loan_total_months - 1 )
print("Your loan amount would be: $%s" % str('{:,}'.format(vehicle_tax)) )
print("Your monthly payment would be: {:.2f}".format(monthly_repayment) )
# repayments
for x in range(1, loan_duration + 1):
for y in range(12):
monthly_interest = (vehicle_tax * interest_rate)
principal = (monthly_repayment - monthly_interest)
vehicle_tax = float(vehicle_tax - principal)
print("Years:", x)
print("Balance remaining: ${:.2f}".format(vehicle_tax))
month = x * 12
print("Total payments: ${:.2f}".format(month*monthly_repayment))
# vehicles in price range
vehicles_in_price_range = []
# get the price list from the csv
price_list = [row[0] for row in car_list]
# get the closest value vehicle
closest_value_vehicle = min(price_list, key=lambda x:abs(int(x)-vehicle_cost))
print(closest_value_vehicle)
for row in car_list:
# price
price = row[0]
# check if price in range
if int(price) == int(closest_value_vehicle):
vehicles_in_price_range.append(row)
print("Vehicle Recomendations:")
# print list of vehicles in price range
for vehicle in vehicles_in_price_range:
print('%s %s %s (VIN: %s) (Millage:%s) (Location: %s, %s) - $%s' %
( vehicle[1],
vehicle[6],
vehicle[7],
vehicle[5],
vehicle[2],
vehicle[3],
vehicle[4],
str('{:,}'.format(int(vehicle[0]))) ) )
Trying to get the user to choose an operation they want to use and then run the respective program. Don't get what is the problem here?
This is my code
from collections import Counter
print (30 * '-')
print (" M A I N - M E N U")
print (30 * '-')
print ("Program 1.Total Populations of the different continents")
print ("Program 2.Percentage Change(%) for different countries")
print (30 * '-')
Input1=1
Input2=2
## Get input ###
choice = int(input('Enter your choice [1-2] : '))
### Take action as per selected menu-option ###
while choice==1 or choice==2:
if (choice == 1):
counter1 = Counter()
with open('a.txt') as f:
for i in range(0,2):
next(f)
for line in f:
splits = line.split(';')
population = int(splits[3])
continent = splits[-1].strip()
counter1[continent] += population
# Print continents sorted by population
for continent, pop_sum in counter1.most_common():
print(continent, ":", pop_sum)
else:
counter2 = Counter()
with open("a.txt") as f:
for i in range(0,2):
next(f)
for line in f:
splits = line.split(';')
change = float(splits[6])
country = splits[1].strip()
counter2[country] += change
#Percentage Change By Countries"
print()
print ("Percentage Change By Countries")
for country, change_sum in counter2.most_common():
print(country, change_sum,"%")
Sample Data
World Population Data 2019 from the United Nations
Rank; Country; 2018; 2019; % Share; Pop Change; % Change; Continent
1; China; 1427647786; 1433783686; 18.6; 6135900; 0.43; Asia
2; India; 1352642280; 1366417754; 17.7; 13775474; 1.02; Asia
3; United States of America; 327096265; 329064917; 4.27; 1968652; 0.60; North America
4; Indonesia; 267670543; 270625568; 3.51; 2955025; 1.10; Asia
5; Pakistan; 212228286; 216565318; 2.81; 4337032; 2.04; Asia
6; Brazil; 209469323; 211049527; 2.74; 1580204; 0.75; South America
7; Nigeria; 195874683; 200963599; 2.61; 5088916; 2.60; Africa
8; Bangladesh; 161376708; 163046161; 2.11; 1669453; 1.03; Asia
9; Russian Federation; 145734038; 145872256; 1.89; 138218; 0.09; Europe
10; Mexico; 126190788; 127575529; 1.65; 1384741; 1.10; North America
First of all, i didn't really understand what you want, but i corrected your indentation problems.
from collections import Counter
print (30 * '-')
print (" M A I N - M E N U")
print (30 * '-')
print ("1.Total Populations of the different continents")
print ("2.Percentage Change(%) for different countries")
print (30 * '-')
## Get input ###
choice = int(input('Enter your choice [1-2] : '))
### Take action as per selected menu-option ###
#1st Operation
print ("Continents Sorted By Population")
while choice==1 or choice==2:
if (choice == 1):
counter1 = Counter()
with open('a.txt') as f:
for i in range(0,2):
next(f)
for line in f:
splits = line.split(';')
population = int(splits[3])
continent = splits[-1].strip()
counter1[continent] += population
# Print continents sorted by population
for continent, pop_sum in counter1.most_common():
print(continent, ":", pop_sum)
#2nd operation
#Percentage Change By Countries
elif choice==2:
counter2 = Counter()
with open("a.txt") as f:
for i in range(0,2):
next(f)
for line in f:
splits = line.split(';')
change = float(splits[6])
country = splits[1].strip()
counter2[country] += change
print()
print ("Percentage Change By Countries")
for country, change_sum in counter2.most_common():
print(country, change_sum,"%")