如何将Powershell脚本中的for循环转换为python代码?
Power Shell脚本
$result = Foreach ($row in $csv)
{ $row
if ($row.Param_Name -eq "p_s3bucket_arn") { $row.Param_Value = $S3Bucketarn }
}
Python代码:
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
执行Python代码时出错:
if(row [0] =='p_instance_count'):
IndexError:列表索引超出范围
CSV
Param_Name,Param_Value
p_instance_count,
p_tag_name,tag123
答案 0 :(得分:1)
看起来像您需要的。
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)
使用csv.DictReader
例如:
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"], ""))