How to store split into an array

Question:

I want to store the values that I splitted in an array. I’ve tried printing it outside of the for loop but it just gives me a single value.

Date            Close/Last     Volume        Open          High           Low
10/06/2021      $142           83221120      $139.47       $142.15        $138.37
def stocks(file) :
    try:
        fh = open(file, 'r')
    except IOError:
        print("error opening file ....", file)
    else:
        arr = {}
        records = fh.readlines()
        for record in records:
            fields = record.split(',')
            arr = fields[2]
        print(arr)
        fh.close()
Asked By: Yanru Shin

||

Answers:

The split function is doing what you’re expecting it to do. However, in the for loop, you’re creating this new variable arr that you’re assigning to fields[2]. I’m assuming you want to append this value to the array. Also,

arr = {}

initializes a dictionary and not an array. With these changes, your code is as follows:

def stocks(file) :
    try:
        fh = open(file, 'r')
    except IOError:
        print("error opening file ....", file)
    else:
        arr = []
        records = fh.readlines()
        for record in records:
            fields = record.split(',')
            arr.append(fields[2])
        print(arr)
        fh.close()
Answered By: Paulina Khew

It looks like you want a list of values in the Volume column of a CSV file.

If you prefer not to import csv then you could do this:

def stocks(file):
    try:
        with open(file) as fh:
            arr = []
            next(fh) # skip column names
            for line in fh:
                if len(tokens := line.split()) >= 3:
                    arr.append(tokens[2])
            return arr
    except Exception:
        print(f'Failed to open {file}')
Answered By: OldBill
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.