【问题标题】:Python: Why is DictWriter writing 'NULL' bytes?Python:为什么 DictWriter 写入“NULL”字节?
【发布时间】:2013-02-11 06:54:51
【问题描述】:
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()

输出: Exception!: line contains NULL byte

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

【问题讨论】:

  • 我猜if i >= self.maxLineswhile True 循环内。而且,请您更正行打印行['name_of_field]。字符串没有终止。
  • 我的猜测是 Reader 正在缓存它之前读取的位置,而不是信任文件位置(您使用 seek(0) 修改过。因为它试图从末尾读取文件,它会得到虚假数据。
  • 它肯定是从文件的开头读取的,因为它告诉我它正在读取 NULL 字节,事实上,file 开头的 NULL 字节不存在第一次条件if numRowsWritten >= self.maxLines: 为真。

标签: python dictionary null python-2.6


【解决方案1】:

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

【讨论】:

  • 这行得通,谢谢。我想知道为什么 truncate 会把事情搞砸。
猜你喜欢
  • 1970-01-01
  • 2014-06-02
  • 2021-01-08
  • 1970-01-01
  • 2018-10-11
  • 2020-05-21
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
相关资源
最近更新 更多