简体   繁体   中英

cannot write bytes to gif file (python)

I'm working on a project that involves taking a stream of bytes and assembling them into a.gif file.

my class for creating a file and writing to it is this:

class fileAdd():
    def create_file(self, input):
        self.filepath = pathlib.Path('gifs/' + input)
        self.fp = open(self.filepath, 'ab')
        print("file created")
    def add_data(self, input):
        self.fp.write(input)
        print("adding data")
    def close(self):
        self.fp.close()

here create_file() takes a filename+extension and creates/opens the file. then, add_data() is repeatedly called to add raw binary data to the file in 140 byte chunks. finally, close() is called to close the file.

here's the problem: add_data() never gets past self.fp.write() , "adding data" never gets printed, and close() doesn't seem to work at all either. this is not an issue with the code calling these functions. if I delete self.fp.write() it prints out "adding data"

why does this happen and how can I fix it?

TIA, Auri.

I am going to take a guess that you are attempting to directly call the functions and have not created an object from your class and then called the functions via your object. Following is a snippet of code I wrote using your class and functions that did pump out data to a binary file.

import pathlib

class fileAdd():
    def create_file(self, input):
        self.filepath = pathlib.Path('gifs/' + input)
        self.fp = open(self.filepath, 'ab')
        print("file created")
    def add_data(self, input):
        self.fp.write(input)
        print("adding data")
    def close(self):
        self.fp.close()

x = b'\x00\x00\x00'

fpx = fileAdd()

fpx.create_file("GIF")

fpx.add_data(x)

fpx.close()

Following is the sample output to the file called "GIF".

@Una:~/Python_Programs/File/gifs$ hexdump GIF
0000000 6548 6c6c 006f 0000                    
0000008

Give that a try and see if that moves you forward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM