我正在嘗試創建一個新的 csv 檔案,該檔案從 CSV 格式檔案的 ASCII 表中評估有關施工現場操作的資料。我已經想出了如何創建一個 CSV 檔案,但我總是在行之間得到一個空行。這是為什么?
import csv
header = ['name', 'area', 'country_code2', 'country_code3']
data = ['Afghanistan', 652090, 'AF', 'AFG']
file_object = open("new_file.csv", "w")
writer = csv.writer(file_object, delimiter=";")
writer.writerow(header)
writer.writerow(data)
file_object.close()
我的 csv 檔案是這樣的:
name area country_code2 country_code3
Afghanistan 652090 AF AFG
uj5u.com熱心網友回復:
指定newline=''以消除額外的新行。
如果在寫入時使用 \r\n 行尾的平臺上未指定 newline='' 將添加額外的 \r。指定 newline='' 應該始終是安全的,因為 csv 模塊執行它自己的(通用)換行處理。[1]
with open('new_file.csv', 'w', newline='') as file_object:
writer = csv.writer(file_object, delimiter=";")
writer.writerow(header)
writer.writerow(data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/376573.html
