Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to store split into an array

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading