【发布时间】:2021-12-13 15:48:01
【问题描述】:
我还是 python 新手,我必须创建一个方法来读取一些 txt 文件并为每个文件返回一个列表,其中包含特定列的值。
我尝试创建一个包含我必须读取的所有文件的数组,并将其作为参数发送到我的方法。
import json, requests, urllib.parse, re
from pandas.io.parsers import read_csv
import pandas as pd
from termcolor import colored
import numpy as np
from glob import glob
import os
# Set Up
dateinplay = "2021-09-27"
cdwenv1 = "cdwu" # Note that it only works with the http version right now
cdwenv2 = "cdwp" # Control Env, usually cdwp
CoreMurexFilesLoc = r"J:\Gerard\Release197\UAT\Files\Core"
# Dev Static
cdwenv = "" # leave empty
files = glob(CoreMurexFilesLoc + "\\*")
# index 1: MHEU_TradeCash_ | 2: TradeCash_
tradeCashfiles = [i for i in files if "TradeCash" in i]
# index 1: MHEU_Trade_ | 2: Trade_
tradeFiles = [i for i in files if "Trade_" in i]
mheu_tradeCash = tradeCashfiles[1]
tradeCash = tradeCashfiles[2]
mheu_trade = tradeFiles[1]
trade = tradeFiles[2]
filesList = [mheu_trade, trade, mheu_tradeCash, tradeCash]
def read_csv(input: list):
for file in list:
df_trade = pd.read_csv(
file,
delimiter="|",
index_col=False,
dtype="unicode",
)
# Drop any blank fields
df_trade.dropna(subset=["MurexCounterpartyRef"], inplace=True)
tradeList = df_trade["MurexCounterpartyRef"]
return tradeList
read_csv(filesList)
但是我收到一个不可迭代对象错误,我不明白为什么我不能通过这个列表进行交互。
Traceback (most recent call last):
File "h:\DESKTOP\test_check\ultimateParent.py", line 50, in <module>
read_csv(filesList)
File "h:\DESKTOP\test_check\ultimateParent.py", line 35, in read_csv
for file in list:
TypeError: 'type' object is not iterable
如果有人可以帮助我识别并解决错误,我将不胜感激。
【问题讨论】:
-
删除函数参数的“input:”
-
请更改变量名 - 不要使用
list,而是使用my_list或array。 -
据我了解,您想使用打字,但您反过来使用了它。正确的方法是
usable_variable: variable_type像def foo(input_variable: type):然后使用input_variable,函数内部的第一个。