1
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

2 回目にfor row in self.csvReader:行がヒットすると、例外がスローされ、ファイルを見ると、ファイルの最初に NULL バイトがたくさんあります。どうやら、ファイルが切り捨てられた後、DictWriter は大量の NULL バイトを書き込んだようです (または、少なくともそれが私の仮定です)。NULL バイトがファイルに書き込まれないようにするにはどうすればよいですか?

4

1 に答える 1

1

どうやら、ファイルを切り詰めることで、ライターの内部状態を台無しにします。切り詰める代わりに、ファイルを閉じてから再度開き (モードw+b切り捨て)、 と を再度初期化しcsvReaderますcsvWriter

于 2013-02-26T16:32:32.980 に答える