我是 Python 新手,我一直在嘗試創建 csv 檔案并將每個結果保存在新行中。結果由幾行組成,每一行都應在 csv 中捕獲。但是,我的 csv 檔案將每個字母分成新行。我還需要為檔案名添加新的鍵值,但我不知道如何獲取影像檔案名(輸入是影像)。我使用搜索欄搜索類似的案例/推薦的解決方案,但仍然很難過。提前致謝。
with open('glaresss_result.csv','wt') as f:
f.write(",".join(res1.keys()) "\n")
for imgpath in glob.glob(os.path.join(TARGET_DIR, "*.png")):
res1,res = send_request_qcglare(imgpath)
for row in zip(*res1.values()):
f.write(",".join(str(n) for n in row) "\n")
f.close()
res1迭代期間列印的字典回傳:
{'glare': 'Passed', 'brightness': 'Passed'}
結果應該是這樣的(得到 3 行):
- 眩光亮度
- 通過 通過
- 通過 通過
- 通過。通過
但是當前的輸出是這樣的:

uj5u.com熱心網友回復:
我改變的東西很少。
w就足夠了,因為t對于文本模式是默認的- 使用背景關系管理器時無需關閉 csv
- 不需要 zip 和
str(n) for n in row. 只需加入字典的 2 個值
更新
with open('glaresss_result.csv','w') as f:
f.write(",".join([*res1] ['filename']) "\n") # replace filename with whatever columnname you want
for imgpath in glob.glob(os.path.join(TARGET_DIR, "*.png")):
res1,res = send_request_qcglare(imgpath)
f.write(",".join([*res1.values()] [imgpath]) "\n") # imgpath (which needs to be a string) will be the value of each row, replace with whatever you suits
uj5u.com熱心網友回復:
如果您打算對資料做更多的事情,您可能需要查看 pandas 庫。在您的用例中 p.exDataFrame.from_records
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.from_records.html
它提供了許多開箱即用的功能來讀取、轉換和寫入資料。
import pandas as pd
results = []
for imgpath in glob.glob(os.path.join(TARGET_DIR, "*.png")):
res1,res = send_request_qcglare(imgpath)
result.append(res1)
df = pd.DataFrame.from_records(results)
df.to_csv("glaresss_result.csv", index=False)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/525994.html
