Home > Back-end >  How do you loop multple iterations using variables from CSV file?
How do you loop multple iterations using variables from CSV file?

Time:10-05

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

CodePudding user response:

You can use csv module to parse the lines.

with open('sample.csv','r') as file:
    for VAR1, VAR2 in csv.reader(file.readlines()[1:]):
        print(f"A code with VAR1={VAR1}, and VAR2={VAR2}")

Replace the print statement with your code.

You can also do it easily without the csv module for instance like this:

with open('sample.csv','r') as file:
    for line in file.readlines()[1:]:
        VAR1, VAR2 = [int(i) for i in line.strip().split(',')]
        print(f"A code with VAR1={VAR1}, and VAR2={VAR2}")
  • Related