代码之家  ›  专栏  ›  技术社区  ›  RustyShackleford

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

  •  0
  • RustyShackleford  · 技术社区  · 7 年前

    我有一个文件夹,里面有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?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Yon P    7 年前

    glob

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