【发布时间】: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上下文管理器。