Python 如何从文件夹中一次读取一个文件,并将数据作为字符串传递到API中,同时将响应写回文件中?

Python 如何从文件夹中一次读取一个文件,并将数据作为字符串传递到API中,同时将响应写回文件中?,python,python-3.x,file,for-loop,Python,Python 3.x,File,For Loop,我有一个包含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

我有一个包含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中

尝试
glob
来迭代*.txt文件

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

尝试
glob
来迭代*.txt文件

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

看看这个,它可能对你有帮助。看看这个,它可能对你有帮助。