gpt4 book ai didi

Python:为什么 DictWriter 写入 'NULL' 字节?

转载 作者:太空宇宙 更新时间:2023-11-03 19:04:34 25 4
gpt4 key购买 nike

class WhatsGoingOn:
def __init__(self, filename, fieldNames, maxLines):
self.file_to_write = filename
self.fieldNames = fieldNames'
self.maxLines = maxLines

# Open the file for reading and writing. Create it if it doesn't exist,
# and truncate it if it does.
self.file = open(self.file_to_write, 'w+b')
self.csvReader = csv.DictReader(self.file, fieldnames=self.fieldNames)
self.csvWriter = csv.DictWriter(self.file, fieldnames=self.fieldNames, extrasaction='ignore')

def looper(self):
# Infinitly (don't worry about that - this is a daemon),
# write to the file. When a certain number of lines have been written,
# read the file and then truncate it.
try:
numRowsWritten = 0
while True:
# Nevermind what's being written
self.csvWriter.writerow({'name_of_field_0': str(numRowsWritten ), 'name_of_field_1': str(numRowsWritten )})
numRowsWritten += 1

if numRowsWritten >= self.maxLines:
# Iterate through each row of the file
self.file.seek(0)

# This only works the first time...
for row in self.csvReader:
print row['name_of_field']

# Truncate the file, and restart the
self.file.truncate(0)
numRowsWritten = 0

except Exception as e:
print 'Exception!: {0}'.format(e)
self.file.close()

输出: 异常!:行包含 NULL 字节

第二次 for row in self.csvReader: 行被命中,抛出异常,当我查看文件时,文件确实有一大堆 NULL 字节开始。显然,在文件被截断后,DictWriter 写入了一大堆 NULL 字节(或者至少这是我的假设)。 如何防止 NULL 字节写入我的文件?

最佳答案

显然,通过截断文件,您会弄乱编写器的某些内部状态。不要截断,而是关闭并重新打开文件(w+b 截断模式),然后重新初始化 csvReadercsvWriter

关于Python:为什么 DictWriter 写入 'NULL' 字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15078683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com