I was making stock data MACD calculator in python. The way of my approach is using 'for()'
to access pickle datas in certain directory and calculate MACD values one by one. However, I got 'Ran out of input error' everytime. I checked my directory where pickle datas are stored and it was not empty. Funny thing is, If I just put numbers in i
position without using 'for()'
, I could get data of the pickle file. Please help me to get free from this error.
Here's my code:
'''
import pickle
import os
import pathlib
from pathlib import Path
file_list = os.listdir('/home/sejahui/projects/pickle_data')
os.chdir('/home/sejahui/projects/pickle_data')
for i in range(2):
odd = file_list[i]
with open(odd,'rb') as stock:
data = pickle.load(stock)
print(data)
'''
In this case, actually, you create a list with file_list = os.listdir('/home/sejahui/projects/pickle_data')
. You do not need range
to iterate.
The error is because sometimes there is only 1 file so it will be out of the index. The correct way is like this:
import pickle
import os
import pathlib
from pathlib import Path
file_list = os.listdir('/home/sejahui/projects/pickle_data')
os.chdir('/home/sejahui/projects/pickle_data')
for str in file_list:
with open(str,'rb') as stock:
data = pickle.load(stock)
print(data)
You can even add an if
statement to the filter based on a regex or pattern
if str == "something":
with open(str,'rb') as stock:
data = pickle.load(stock)