處理包含標頭的CSV(逗號分隔值)檔案時,通常需要在處理過程中排除這些標頭。本文解決了嘗試在 Python 中跳過標題時遇到的常見問題。
提供的程式碼片段遇到標題行受應用函數影響的問題。要修正此問題,讀者應注意 reader 變數會迭代 CSV 檔案中的行。
要在主循環之前跳過一行(其中行索引從1 開始),請使用next() 函數,如下所示:
next(reader, None) # Skip header by returning None if the reader is empty
此外,為了增強可讀性並簡化文件處理,上下文管理器可以被雇用:
with open("tmob_notcleaned.csv", "rb") as infile: with open("tmob_cleaned.csv", "wb") as outfile: reader = csv.reader(infile) next(reader, None) # Skip headers writer = csv.writer(outfile) for row in reader: # Process rows here
或者,要在輸出檔案中包含標題行,只需將headers 變數(可以使用next() 初始化)傳遞給writer:
headers = next(reader, None) # Get headers or None if empty if headers: writer.writerow(headers)
透過遵循這些技術,開發人員可以有效地跳過標題並輕鬆處理 CSV 檔案。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3