[英]How to create user-defined function with Python list?
這是我想將 package 轉換為 function 的代碼部分。 我這樣累
def mm(*files, writer=None):
for file in files:
if fnmatch.fnmatch(file, 'ticr_calculated_2*'):
gunzip(file, file.replace(".gz", ""))
json_fi = glob.glob("*.json")
table_list=[]
for filename in json_fi:
with open(filename, encoding='utf-8', mode='r') as i:
data = pd.read_json(i, lines=True)
table_list.append(data)
for table in table_list:
writer = append_to_parquet_table(table, filepath, writer)
if writer:
writer.close()
return writer
稍后我將有 'tick_calculated_3*' 和類似的文件名。
我調用了我的 function
files = [fi for fi in files if fi.endswith(".gz")]
mm(files,writer)
文件是列表類型,它必須保持這種狀態。
我有錯誤
File "/usr/local/Cellar/python@3.8/3.8.3/Frameworks/Python.framework/Versions/3.8/lib/python3.8/posixpath.py", line 54, in normcase
return os.fspath(s)
TypeError: expected str, bytes or os.PathLike object, not list
您可以將 * 與您的參數一起使用,這將在一個元組中捕獲任何傳遞的 arguments:
def f(*filenames):
# filenames is a tuple with all your arguments and you can iteratore over
print(type(filenames)) # prints <class 'tuple'>
for arg in args:
pass # do something here
如果您還想要一個位置參數(在您的情況下為 writer),它必須作為第一個參數放置:
def f(writer, *filenames):
print(writer)
print(len(filenames)) # will be zero if only a writer is passed
print(type(filenames))
在您的情況下,使用以下內容就足夠了:
def mm(filenames): # you can pass anything that is iterable (list, tuples, strings, ...)
for file in filenames:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.