-7

I need to write a Python program to read/close the file (i.e., Stock.txt), and display the following output, using the split method of list. There is only one line in the Stock.txt which is the stock portfolio of an investor, consisting of the invested amount of four stocks.

Inside content of the file Stock.txt:

hsbc, 84564.24, boc, 46392.45, manulife, 34562.98, galaxy, 89321.23

I only know how to write related Python code to open to read/close the file. I really don't know what python code I should write to display the following expected output which the assignment requires me to do!

My current code:

infile = open("Stock.txt", 'c')
data = [line.rstrip() for line in infile]

infile.close()

But I am not sure whether my current code is right since I am a Python beginner.

Expected output of this assignment:

01234567890123456789012345678901234567890123456789

The amount invested in HSBC:       844563.24
The amount invested in BOC:        465392.46
The amount invested in MANULIFE:   345612.98
The amount invested in GALAXY:     893421.23

STOCK      PERCENTAGE
---------------------
HSBC           33.13%
BOC            18.26%
MANULIFE       13.56%
GALAXY         35.05%

Total Amount Invested: $2,548,989.91

1 Answers1

-1

I don't think I'm allowed to fully solve it for you, but I can get you started.

first_line = data[0] # 'hsbc, 84564.24, boc, 46392.45, manulife, 34562.98, galaxy, 89321.23'
real_data = first_line.split(', ') # ['hsbc', '84564.24', 'boc', '46392.45', 'manulife', '34562.98', 'galaxy', '89321.23']

There is one line in our file, so we take the first line with data[0], then split into a list with .split(', ').

stock_names = real_data[::2] # ['hsbc', 'boc', 'manulife', 'galaxy']
stock_values = real_data[1::2] # ['84564.24', '46392.45', '34562.98', '89321.23']

The first line gets every second element of real_data starting from the 0th. The first line gets every second element of real_data starting from the 1st. Both use the list splicing syntax: list[start:end:step] Understanding slice notation

for name, value in zip(stock_names, stock_values):
    print(name, value)
    # perform calculations ect. 

All together:

infile = open("stocks.txt", 'r')
infile.close()
data = [line.rstrip() for line in infile]
first_line = data[0]
real_data = first_line.split(', ')
stock_names = real_data[::2]
stock_values = real_data[1::2]
for name, value in zip(stock_names, stock_values):
    print("something")
    # perform calculations
# Good luck :)

Note I have moved infile.close() to the beginning as there is no need for the file to be open for the whole time.