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