python - 如何从文件夹一次读取一个文件并将数据作为字符串传递到 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?
解决方案
尝试glob
遍历 *.txt 文件。
Import glob
f = “./path/to/file/*.txt”
for files in glob.glob(f)
with open(files) as f:
#do your code here
推荐阅读
- r - 抓取在线地图
- android - Android Jetpack Navigations:从“非导航”片段导航
- c# - 如何从骰子脚本中获取骰子值到石头脚本
- django - Django Modelforms:如何显示 CharField 的选择?
- java - 如何解决 DTO 的 modelMapper 错误?
- javascript - 向 Nativescript 元素添加伪选择器
- vbscript - 通过 UFT 执行存储在网络驱动器上的 VBS 文件
- c# - MeterialDesign WPF PackIcon 绑定类型
- docker - 无法使用docker连接到气流中的postgres数据库
- java - 多次调用 Java 服务类加载器