How do you loop multple iterations using variables from CSV file?

Question:

I am trying to run the following in iterations pulling VAR1 and VAR2 from a CSV file called sample.csv and inserting them into the matching spots below and looping the function for each row in the CSV file.

import http.client
import json

conn = http.client.HTTPSConnection("a.b.com")
payload = json.dumps({
  "node_list": [
    {
      "id": VAR1,
      "with_descendants": True
    }
  ]
})
headers = {
  'Content-Type': 'application/json',
  'Cookie': 'A'
}
conn.request("PUT", "/poweruser/v1/powerusers/VAR2/branches?access_token=xyz", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

Sample.csv:

VAR1,VAR2
10,20
30,40
50,60
70,80

Asked By: silentmyst

||

Answers:

You can use csv module to parse the lines.

with open('sample.csv','r') as file:
    reader = csv.reader(file)
    next(reader) # this is to skip the first line in the csv file
    for VAR1, VAR2 in reader:
        print(f"A code with VAR1={VAR1}, and VAR2={VAR2}")

Replace the print statement with your code.

Answered By: Ondrej Draganov
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.