I have a python function with a variable file. My problem is now, I want to work with the filename.
My problem now is, the type of variable is not known automatically inside of the function. What easy possibilities do I have to determine the variable to be a file?
import pandas_datareader as web
import pandas as pd
import pickle
def import_prices(file, start, end):
tickers = pickle.load(file)
main_df = pd.DataFrame()
i = 0
for ticker in tickers:
df = web.DataReader(ticker, 'yahoo', start, end)
df.rename(columns={"Adj Close": ticker}, inplace=True)
df.drop(columns=["Open", "High", "Low",
"Close", "Volume"], inplace=True)
if main_df.empty:
main_df = df
else:
main_df = main_df.join(df, how='outer')
i = i 1
print(i)
main_df.to_csv('Webscrapper/{}_prices.csv'.)
the filename without the stuff after the dot I want to insert into the brackets of
main_df.to_csv('Webscrapper/{}_prices.csv'.)
CodePudding user response:
The file
variable should contain a filename as I see in your code. You could check the following to be sure that the file contains a string value isinstance(file, str)
.
You could also use more complex checks like isinstance(file, pd.DataFrame)
or
from io import IOBase
isinstance(someobj, IOBase)
It would be better to use type hints in the function definition. I assume that start
and end
are ints but you could change this to match the right type.
def import_prices(file: str, start: int, end: int) -> None