读取目录中的文件并动态保存每个文件

问题描述 投票:0回答:1
text_open = open("inputfiles/(22).txt", "r")
text = text_open.read()

doc = nlp(text)
db.add(doc)
db.to_disk("./outputfiles/22.spacy")

我正在尝试遍历 inputfiles 文件夹中的 500 多个文档中的每一个,并通过 db.to_disk 输出它们。我不是每次都更改硬编码数字,而是如何动态重命名每个新输出文件以匹配输入文件?

如果我用 glob/os 打开目录,我如何将它添加到输出目录而不用硬编码的“22”覆盖每个文件或创建新的 22(1).spacy, 22(2).spacy等文件?

谢谢!

python spacy
1个回答
0
投票

如果您使用的是 Python 3.6+,请使用

f-string
s。

for i in range(1, 501):
    text_open = open(f"inputfiles/({i}).txt", "r")
    text = text_open.read()

    doc = nlp(text)
    db.add(doc)
    db.to_disk(f"./outputfiles/{i}.spacy")

有帮助吗?

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