Home > OS >  How to store split into an array
How to store split into an array

Time:10-14

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()

CodePudding user response:

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()

CodePudding user response:

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}')
  • Related