I have a folder with different files of stock prices that I need to pull into python and then save to a dictionary. I'm trying to do this with a for loop and a list of names. Currently, when I run my code the console just sits there loading forever and never outputs anything or signals that it is done. This is what I currently have:
# Dictionary
results = {}
#Read in data from files (example: AAPL.txt)
tickers = ["AAPL", "ADBE", "DAL", "F", "GOOG", "GPRO", "NCLH", "NFLX", "RUN", "SBUX"]
for ticker in tickers:
file = open("/user/code/"<ticker>".txt")
lines = file.readlines()
results["<ticker>_prices"].append(float(lines))
print(results)
This code doesn't even run, the console just runs and runs and the dictionary results = {}
is still empty if I stop it and check.
CodePudding user response:
Execute the following statement:
for ticker in tickers:
print("/user/code/"<ticker>".txt")
The output is all true.
Maybe you should do this:
file = open("/user/code/" ticker ".txt")
CodePudding user response:
IIUC, this should work. Since each ticker
is a file name, you could open and read each file, then map each line to a float and assign to results
under key f"{ticker}_prices"
:
results = {}
for ticker in tickers:
with open(f"/user/code/{ticker}.txt") as file:
lines = file.readlines()
results[f"{ticker}_prices"] = list(map(float, lines))