[英]Python: define type of variable given into a function parameter
I have a python function with a variable file.我有一个带有变量文件的 python 函数。 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'.) main_df.to_csv('Webscrapper/{}_prices.csv'.)
The file
variable should contain a filename as I see in your code. file
变量应包含我在您的代码中看到的文件名。 You could check the following to be sure that the file contains a string value isinstance(file, str)
.您可以检查以下内容以确保文件包含字符串值isinstance(file, str)
。
You could also use more complex checks like isinstance(file, pd.DataFrame)
or您还可以使用更复杂的检查,如isinstance(file, pd.DataFrame)
或
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.我假设start
和end
是整数,但您可以更改它以匹配正确的类型。
def import_prices(file: str, start: int, end: int) -> None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.