1

How can I convert a for loop in Powershell script to python code?

Power shell script

 $result = Foreach ($row in $csv)
 {   $row   
 if ($row.Param_Name -eq "p_s3bucket_arn") { $row.Param_Value = $S3Bucketarn }
 }

Python Code:

   with open('C:/test.csv') as csvfile:
   readCSV = csv.reader(csvfile, delimiter=',')
   for row in readCSV:
      if(row[0]=='p_instance_count'):
        row[1]=len(instance_count)   # expecting to write in csv file as p_instance_count,10
        

Error while Executing Python Code:

if(row[0]=='p_instance_count'):

IndexError: list index out of range

CSV

Param_Name,Param_Value
p_instance_count,
p_tag_name,tag123
2
  • list index out of range for row[0] means your row contains nothing. can you add contents of your csv file with the question? Commented Sep 23, 2019 at 8:28
  • Improve formatting Commented Sep 23, 2019 at 9:33

1 Answer 1

1

Looks like you need.

data = []
with open('C:/test.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    next(readCSV)   #skip header
    for row in readCSV:
        if row[0]=='p_instance_count':
            data.append((row[0], len(instance_count)))   
        else:
            data.append((row[0], ""))

with open('C:/test.csv', "w") as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    for row in data:
        writer.writerow(row)

Using csv.DictReader

Ex:

data = []
with open('C:/test.csv') as csvfile:
    readCSV = csv.DictReader(csvfile, delimiter=',')
    for row in readCSV:
        if row["Param_Name"]=='p_instance_count':
            data.append((row["Param_Name"], len("instance_count")))   
        else:
            data.append((row["Param_Name"], ""))
Sign up to request clarification or add additional context in comments.

2 Comments

I am getting if (row[0] == 'p_instance_count'): IndexError: list index out of range do not know where to change.
Can you try using DictReader

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.