Reputation: 448
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
Upvotes: 1
Views: 1889
Reputation: 82785
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"], ""))
Upvotes: 1