首页 > 解决方案 > 如何从文件夹一次读取一个文件并将数据作为字符串传递到 API,同时将响应写回文件?

问题描述

我有一个包含 500 个文本文件的文件夹。文本文件包含我想要发送到 API 的数据。我想将 API 中的响应对象写入另一个文本文件的文件夹中。

到目前为止,这是我循环浏览文件夹中文件的代码。但是,这会遍历所有文件:

import os

directory = os.path.normpath("file path to folder")
for subdir, dirs, files in os.walk(directory):
    for file in files:
        if file.endswith(".txt"):
            f=open(os.path.join(subdir, file),'r')
            a = f.read()
            print a
            r = requests.post(url1,data=a).content
            file = 'file path to write api response'
            f = open(file, 'a+')
            f.write(r)
            f.close()

如何一次只循环一个文件并将结果传递给 api?

标签: pythonpython-3.xfilefor-loop

解决方案


尝试glob遍历 *.txt 文件。

Import glob
f = “./path/to/file/*.txt”
for files in glob.glob(f)
    with open(files) as f:
        #do your code here

推荐阅读