一个从多个文本文件中提取URL的循环

问题描述 投票:0回答:2

我正在尝试使用for循环从多个文件中提取URLS列表,但是这导致仅从第一个文件中提取URLS列表,重复10次。我不确定自己在做什么错。另外,我绝对是对此的初学者,所以我假设有很多更好的方法来实现我想要的目标,但这是我到目前为止的目标。

type_urls = []
y = 0

for files in cwk_dir:
    while y < 10:
        open('./cwkfiles/cwkfile{}.crawler.idx'.format(y))
        lines = r.text.splitlines()
        header_loc = 7
        name_loc = lines[header_loc].find('Company Name')
        type_loc = lines[header_loc].find('Form Type')
        cik_loc = lines[header_loc].find('CIK')
        filedate_loc = lines[header_loc].find('Date Filed')
        url_loc = lines[header_loc].find('URL')
        firstdata_loc = 9
        for line in lines[firstdata_loc:]:
            company_name = line[:type_loc].strip()
            form_type = line[type_loc:cik_loc].strip()
            cik = line[cik_loc:filedate_loc].strip()
            file_date = line[filedate_loc:url_loc].strip()
            page_url = line[url_loc:].strip()
            typeandurl = (form_type, page_url)
            type_urls.append(typeandurl)
        y = y + 1

python for-loop extract
2个回答
0
投票

当您进入第二个文件时,while条件失败,因为y已经为10。尝试在while循环之前将y设置回0:

for files in cwk_dir:
    y = 0
    while y < 10:
        ...

而且,当您在while循环内的第一行中打开文件时,退出循环时可能需要关闭该文件。


0
投票

[这是使用pathlib和Python 3的更Python化的方式:

pathlib

如果您发布一个更完整的示例,我可以扩大答案并为您提供更多有用的信息。

© www.soinside.com 2019 - 2024. All rights reserved.