Writing Python Dictionaries to CSV Files
If you need to write a Python dictionary to a csv file, where the dictionary keys appear in the first row and the key values in the second, employ the following approach:
Step 1: Use DictWriter.writerow()
The code you cited uses DictWriter.writerows() which expects a list of dictionaries, not a single dictionary. To write a single row, utilize DictWriter.writerow():
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() w.writerow(my_dict)
Step 2: Include DictWriter.writeheader()
If you desire a header row for your CSV file, call DictWriter.writeheader() before writing the dictionary:
w.writeheader() w.writerow(my_dict)
Step 3: Utilize the "with" Statement
The "with" statement handles file opening and closing elegantly, even during exceptions:
with open("mycsvfile.csv", "w", newline="") as f: # ...
Step 4: Disable Newline Management
The CSV writer manages line breaks internally, so disable the default behavior in open() using newline="":
with open("mycsvfile.csv", "w", newline="") as f: # ...
This revised code generates a CSV file with the dictionary keys and values correctly separated:
test,testing 1,2
以上是如何將 Python 字典寫入 CSV 文件,其中鍵和值位於單獨的行中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!