在python中读取的格式错误的csv - python

我收到的CSV文件格式错误(无法控制生成此CSV的应用程序)

CSV的标题和第一行如下所示:

"Start Time"
"End Time"
"Service"

"255/06:06:54","255/06:54:42","S2 AVAIL"

这是我用来读取csv的代码:

import csv
import os
import sys
rootPath = 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')])

参考方案

最后,我选择以正确的格式重写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()

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…

Python:传递记录器是个好主意吗? - python

我的Web服务器的API日志如下:started started succeeded failed 那是同时收到的两个请求。很难说哪一个成功或失败。为了彼此分离请求,我为每个请求创建了一个随机数,并将其用作记录器的名称logger = logging.getLogger(random_number) 日志变成[111] started [222] start…

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…