0

I have a folder with 500 text files. The text files hold data that I want to send into an API. I want to write the response object from the API into another text file into a folder.

This is my code so far to loop through the files in the folder. However this loops through all the files:

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()

How do I only loop through one file at a time and pass the result into the api?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
RustyShackleford
  • 3,462
  • 9
  • 40
  • 81

1 Answers1

3

Try glob for iterating over the *.txt files.

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