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