【发布时间】:2020-01-23 04:53:15
【问题描述】:
我有一个 power shell 脚本和 python 脚本,可以将数据写入一个常见的 CSV 文件。如果我在 python 脚本中使用关键字“w+”,它会删除旧数据并替换为新数据。如果我使用关键字“a+”,它会继续附加不受欢迎的数据。现在我正在尝试只更新 CSV 文件的特定键列中的值。
我需要帮助来了解如何解决它。
Test.csv =>includes =>
Param_Name,Param_Value
p_resource_name,res123 #prints from powershell script
p_tag_name,tag123 #prints from powershell script
p_instance_count,0 #prints from Python script
p_volume_count,0 #prints from Python script
Powershell.ps1=>
$file_path="C:\test.csv"
$csv = Import-Csv -Path $file_path
$result = Foreach ($row in $csv)
{
$row
if ($row.Param_Name -eq "p_instance_count") { $row.Param_Value = $instance}
if ($row.Param_Name -eq "p_volume_count") { $row.Param_Value = $volume}
}
Python.py =>
f = csv.writer(codecs.open("C:/test.csv", "ab"), lineterminator="\n")
instances = conn.instances.filter(Filters=[{'Name': 'instance-state-name',
'Values': ['running', 'stopped']}])
for instance in instances:
instance_count.append(instance)
instanceCount = str(len(instance_count))
f.writerow(('p_instance_count', len(instance_count)))
所以这是我的代码,首先我运行 Powershell,它应该更新 csv,然后我运行一个 python 脚本,它再次使用计数更新相同的 CSV。
谁能推荐一个更新它的好方法。
【问题讨论】:
标签: python python-2.7 powershell csv