如何將 Python 字典寫入 CSV 檔案:標題行包含鍵,第二行包含值?

Linda Hamilton
發布: 2024-10-17 18:57:02
原創
732 人瀏覽過

How to Write Python Dictionaries to CSV Files: Header Row with Keys, Values in Second Row?

Writing Python Dictionaries to CSV Files

Question:
How can I write a Python dictionary to a CSV file, with the keys as the header row and the values in the second row?

Answer:
To achieve this, you must utilize the csv module and the DictWriter class. However, the code snippet provided in your question only writes the keys to the first line due to an incorrect method usage.

Incorrect Usage:

<code class="python">w.writerows(my_dict)</code>
登入後複製

Correct Usage:

To write a single row of data to a CSV file, use the writerow() method instead.

<code class="python">w.writerow(my_dict)</code>
登入後複製

Example:

<code class="python">import csv

my_dict = {"test": 1, "testing": 2}

with open("mycsvfile.csv", "w", newline="") as f:
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()  # Write header (keys)
    w.writerow(my_dict)  # Write values</code>
登入後複製

Result:

<code class="csv">test,testing
1,2</code>
登入後複製

Additional Notes:

  • The DictWriter expects a list of dictionaries as input, so in this case, we wrap the dictionary in a single-item list.
  • The with statement ensures proper file handling, including automatic file closing.
  • Disable newline management in open() by setting newline="", as the CSV writer handles newlines.

以上是如何將 Python 字典寫入 CSV 檔案:標題行包含鍵,第二行包含值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!