0

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()
5
  • 2
    Could you add an example of the input file? Commented Oct 13, 2022 at 15:43
  • 1
    arr is a dict. What is arr = fields[2] supposed to do? Did you mean arr[fields[2]] = fields? (Also, you probably want to have a look at the csv module.) Commented Oct 13, 2022 at 15:47
  • You'll need to append it to the array using the list.append() method. Commented Oct 13, 2022 at 15:47
  • There are no arrays in this code. Now that you've edited the question to show sample data I suggest you refer to the csv module as that is what your data appears to be Commented Oct 13, 2022 at 15:52
  • @PaulinaKhew I have added an example for the input file. The index is supposed to be Volume and I am trying to store its values Commented Oct 13, 2022 at 15:53

2 Answers 2

2

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.