从搜索返回列表中的索引

2024-04-27 01:11:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个名称列表(cust_name)来查找列表中的任何名称是否存在于文件夹中的任何电子邮件文件中。然后我想用搜索找到的名称创建一个id为cust_id的文件夹,并将电子邮件文件复制到新文件夹中。我有搜索工作,但我不知道如何知道搜索在cust_name中找到哪个索引,所以我可以使用cust_id中相同的索引位置来命名新文件夹。代码如下:

for root,dirs,file in os.walk(os.getcwd()):
    for cur_file in file:
        with open(cur_file, "r") as f:
            content = f.readlines()
                for line in content:
                    line = line.lower()
                    if any(word in line for word in cust_name):
                     #grab index position with search hit in cust_name
                     #grab same index position with search hit in cust_id
                     #create new folder and copy email file

我已经知道如何创建文件夹并复制文件。我的问题是抓住那个索引位置。你知道吗

每当我试图使用word来获取索引位置时,我都会得到一个错误:word没有定义,四处搜索也没有给我任何关于如何获取索引位置的线索。有人有什么建议或者以前做过吗?你知道吗


Tags: 文件namein文件夹名称id列表for
2条回答

如果只需要索引,可以按照dhdavvie的建议使用枚举。对于您的用例,您还可以考虑第一个zippingcust\u id和cust\u name以及数组:

cust_tuples = zip(cust_id, cust_name)

for root, dirs, file in os.walk(os.getcwd()):
    for cur_file in file:
        with open(cur_file, "r") as f:
            content = f.readlines()
            for line in content:
                line = line.lower()
                for cust_id, cust_name in cust_tuples:
                    if cust_name in line:
                        # do things with cust_id
                        break  # if you only want the first hit

你是说这个吗?你知道吗

for index, line in enumerate(content):

相关问题 更多 >