【问题标题】:Python readline ignoring header in csv filePython readline忽略csv文件中的标题
【发布时间】:2019-12-01 09:42:16
【问题描述】:

我编写了一些代码,应该知道 CSV 文件是否存在,如果格式正确则附加到它,或者删除它并创建一个新文件。

它检查格式是否正确的部分(通过检查 CSV 标头以查看它们是否相等)不起作用,因为出于某种奇怪的原因,readline() 函数忽略了标头(这应该是第一个CSV 文件的行。

请注意,我不想使用额外的依赖项,例如 Pandas。

    import os, csv

    path = 'intent_outputs.csv'
    response = {'query':'eggs', 'header':'eggs', 'fulfillmentText':'are tasty', 'buttontext':'VISIT PAGE', 'buttonurl':'eggs.com', 'contextbuttontext':'eggs', 'contextbuttonurl':'eggs.com'}
    output = open(path, 'a')
    csv_columns = ['Query', 'Header', 'Text', 'Button Text', 'Button URL', 'Context Button Text', 'Context Button URL']
    writer = csv.DictWriter(output, fieldnames=csv_columns)
    if not os.path.exists(path):
        print("DOES NOT EXIST")
        output = open(path, 'w')
    else:
        print("EXISTS")
        output = open(path, 'r')
    if(output.readline() != ",".join(csv_columns)):
        print("NOT EQUAL")
        try:
            output = open(path, 'w')
            writer.writeheader()
        except IOError:
            print("IOError")
    else:
        print("EQUAL")
        output = open(path, 'a')
    try:
        row = {'Query':response['query'], 'Header':response['header'], 'Text':response['fulfillmentText'], 'Button Text':response['buttontext'], 'Button URL':response['buttonurl'], 'Context Button Text':response['contextbuttontext'], 'Context Button URL':response['contextbuttonurl']}
        writer.writerow(row)
    except IOError:
        print("I/O error") 

这里是 约翰尼 intent_outputs.csv:

Query,Header,Text,Button Text,Button URL,Context Button Text,Context Button URL
eggs,eggs,are tasty,VISIT PAGE,eggs.com,eggs,eggs.com

我想阅读第一行(以“Query....”开头),但它被主动忽略了。

【问题讨论】:

  • 您似乎用output = open(path, 'a') 和后来的output = open(path, 'w') 打开文件,而没有在两者之间关闭文件;这似乎是意外行为的喘息地。你确定这是个好方法吗?
  • 我使用了这些标签,因为在前者中我必须提供一个 open() 的实例来初始化 csv.DictWriter()'a' 标志是为了防止覆盖并允许附加到文件,如果所有if-else 检查通过),而在后者中,'w' 标签是这样我可以擦除文件并覆盖新的标题。不过,我不确定这是个好主意......
  • Ralf 指出的问题不是标志,而是您打开文件两次而没有在中间关闭它的事实。您可能应该调整逻辑以使用 with open(my_file, flag) as foo 上下文管理器。

标签: python csv io readline


【解决方案1】:

最终自己解决了这个问题。所以我重写了函数,使其不依赖于打开的文件,除了上面代码中的一些额外的逻辑错误之外,下面的脚本可以正常工作。

@Suitsense 的回答让我知道readline() 末尾添加的\n,所以谢谢!

    path = 'intent_outputs.csv'
    response = {'query':'eggs', 'header':'eggs', 'fulfillmentText':'are tasty', 'buttontext':'VISIT PAGE', 'buttonurl':'eggs.com', 'contextbuttontext':'eggs', 'contextbuttonurl':'eggs.com'}
    csv_columns = ['Query', 'Header', 'Text', 'Button Text', 'Button URL', 'Context Button Text', 'Context Button URL']
    output = ""
    writer = ""
    try:
        output = open(path,'x')
    except FileExistsError:
        output = open(path,'r')
    if(open(path,'r').readline() != ",".join(csv_columns)+"\n"):
        try:
            output = open(path, 'w')
            writer = csv.DictWriter(output, fieldnames=csv_columns)
            writer.writeheader()
        except IOError:
            print("IOError: Couldn't write header")
    else:
        output = open(path, 'a')
        writer = csv.DictWriter(output, fieldnames=csv_columns)
    row = {'Query':response['query'], 'Header':response['header'], 'Text':response['fulfillmentText'], 'Button Text':response['buttontext'], 'Button URL':response['buttonurl'], 'Context Button Text':response['contextbuttontext'], 'Context Button URL':response['contextbuttonurl']}
    writer.writerow(row) 

【讨论】:

    【解决方案2】:

    readline() 输出在末尾包含换行符 \n 字符。 所以output.readline()返回

    Query,Header,Text,Button Text,Button URL,Context Button Text,Context Button URL\n

    也许这就是为什么这个条件if(output.readline() != ",".join(csv_columns)): 返回True

    【讨论】:

    • 呃,不是吗?刚刚测试过,它还没有为我返回True
    • 哦,对不起...您可以发布输出日志或堆栈跟踪吗?
    • 没有日志记录或堆栈跟踪。程序运行时不会出现异常。它总是忽略 CSV 的第一行,这很奇怪。
    猜你喜欢
    • 2014-05-08
    • 2018-03-25
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    相关资源
    最近更新 更多