亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在python中讀取的錯誤格式csv

在python中讀取的錯誤格式csv

肥皂起泡泡 2021-06-14 05:08:40
我收到了格式錯誤的 csv 文件(無法控制生成此 CSV 的應用程序)CSV 的標題和第一行如下所示:"Start Time""End Time""Service""255/06:06:54","255/06:54:42","S2 AVAIL"這是我用來讀取 csv 的代碼:import csvimport osimport sysrootPath = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))inputFile = open(rootPath + '\\input\\' + sys.argv[1], 'rt')sys.path.append(rootPath + '\\common')    for row in csv.reader(inputFile, dialect='excel'):        if row:            print(row)這是我收到的輸出:['???"Start Time"']['End Time']['Service']['255/06:06:54', '255/06:54:42', 'S2 AVAIL']第一個問題是奇怪的字符(可能缺少編碼選項?)標題也是錯誤的,不能在該格式上使用 DictReader,這對于我必須使用 CSV 進行的編輯很有用。我可以用正確格式的標題重新編寫一個新的 CSV,這不是問題,但我不知道如何跳過 CSV 的前 3 行???或者我可以用即將到來的 CSV 格式閱讀它嗎?這是我希望使用 csv.reader 獲得的輸出:['Start Time', 'End Time', 'Service']['255/06:06:54', '255/06:54:42', 'S2 AVAIL']或使用 csv.DictReader:OrderedDict([('Start Time', '255/06:06:54'), ('End Time', '255/06:54:42'), ('Service', 'S2 AVAIL')])
查看完整描述

1 回答

?
慕姐4208626

TA貢獻1852條經驗 獲得超7個贊

最后,我選擇以正確的格式重寫 CSV,然后使用它,在實現的解決方案中,新 CSV 中也忽略了 BOM 標記,無論如何,向我建議的有關 BOM 的鏈接包含該問題的修復程序!


這里是我的解決方案實現的代碼:


import csv

import os

import sys

rootPath = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))

sys.path.append(rootPath + '\\common')

from function import *


inputFile = open(rootPath + '\\input\\' + sys.argv[1], 'r')

outputFile = open(rootPath + '\\input\\formatted.csv', 'w', newline='')

writeFile = csv.writer(outputFile)

writeFile.writerow(['StartTime','EndTime','Service'])

for row in csv.reader(inputFile.readlines()[3:], dialect='excel'):

    if row:

        writeFile.writerow(row)

inputFile.close()

outputFile.close()


查看完整回答
反對 回復 2021-06-16
  • 1 回答
  • 0 關注
  • 180 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號