簡體   English   中英

如何在不使用 python 追加新行的情況下更新 csv 文件?

[英]How to update a csv file without appending new rows using python?

我有一個強大的 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 腳本再次更新相同的 ZCC8D68C5501CDEA9ADDZ5 個計數。

任何人都可以提出一個更新它的好方法。

這個問題對我來說似乎不是很清楚。 當您要更新 CSV 文件時,您必須閱讀它,在 memory 中對其進行修改,並在其整個中重寫新創建的實例列表。

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))

順便說一句,請注意對 python2.7 的支持將在 4 個月內結束……您應該切換到 python3

instances變量僅包含您要更改的行(據我了解)

instance_count是一個新列表,應該包含原始列表中的所有行。

csv 文件是一個順序文件。 因此,您甚至不應該考慮在不重寫整個文件的情況下更改字段中的值。 當然也有例外,但我建議這樣做太容易出錯了。

常見的方法是讀取文件,寫入副本並在成功時重命名所有內容。 標准庫文件輸入模塊帶有一個fileinput inplace=True選項,它在幕后執行它:

如果關鍵字參數 inplace=True 被傳遞給 fileinput.input() 或 FileInput 構造函數,則文件被移動到備份文件,標准 output 被定向到輸入文件(如果與備份文件同名的文件已經存在,它將被靜默替換)。 這使得編寫一個過濾器來重寫其輸入文件成為可能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM