![](/img/trans.png)
[英]Dict Key and Value populated from splitting each item in a python list
[英]Python - Write each item from a dict's key to a new line
我認為這應該相當簡單,但我找不到適合我情況的寫入解決方案。 我有字典,每個鍵都有一個列表。 對於字典中的每個鍵,我想打開一個 csv 文件並將每個列表中的每個項目寫入一個新行。 As the program loops through the dict, a new csv file is created for each key, lines for each item in the list for that key are written to a csv, and then the csv closes so the next csv can be created for the next key :
for k, v in Dict.items():
name = "coQ" + str(k) + ".csv"
cPath = r"C:\Path"
coQ = os.path.join(cPath, name)
company_file = open(coQ, 'w')
for i in v:
company_file.write(str(i))
company_file.close()
這會將列表寫入 csv 但所有列表項都在 csv 輸出中的同一行上。 我試過用 append 'a' 打開,但我得到了相同的結果,我不認為換行會起作用,因為它不是新行,而是列表中需要寫入的項目。
嘗試:
for k, v in Dict.items():
name = "coQ" + str(k) + ".csv"
cPath = r"C:\Path"
coQ = os.path.join(cPath, name)
company_file = open(coQ, 'w')
for i in v:
company_file.write("\n")
company_file.write(str(i))
company_file.close()
或者正如帕特里克所說:
for k, v in Dict.items():
name = "coQ" + str(k) + ".csv"
cPath = r"C:\Path"
coQ = os.path.join(cPath, name)
company_file = open(coQ, 'w')
for i in v:
company_file.write(str(i)+'\n')
company_file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.