根据多个文件夹中的关键字删除txt文件

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

我从 edgar 下载了一堆 10-ks。我只需要保留包含关键字“cryptocurrency”和“blockchain”的 10-k 报告。每个公司都有一个文件夹。但是,我被困在从多个文件夹中读取 txt 文件。以下是我的编码:

第 1 步(这部分运行良好并生成正确的目录)

import os
import pandas as pd

path = 'C:/test/2014/QTR1/'
words = ['cryptocurrency', 'blockchain']

filelist = os.listdir(path)

Path2 = []
for x in filelist:
    Path2.append(path + x+ '/')
print(Path2)

第二步:

for i in Path2:
    filelist2 = os.listdir(i)
    for j in filelist2:
        if j.endswith('.txt'):
                
                each_file_content = open(j, 'r', encoding="utf-8").read()
                if not any(word in each_file_content for word in words):
                    os.unlink(j)

运行后,Jupyter 注意到我下面的错误:

FileNotFoundError Traceback (most recent call last) Input In [43], 在 () 3 对于文件列表 2 中的 j: 4 if j.endswith('.txt'): ----> 6 each_file_content = open(j, 'r', encoding="utf-8").read() 7 如果没有(每个文件内容中的单词为单词中的单词): 8 操作系统取消链接(j)

FileNotFoundError: [Errno 2] 没有这样的文件或目录: '0001000180-14-000019.txt'

谁能帮我修改上面的代码或任何其他想法如何完成我提到的任务?提前谢谢你!

我希望删除不包含这两个关键字的文件,任何建议都会有所帮助!

pandas file-read edgar
© www.soinside.com 2019 - 2024. All rights reserved.