umbe1987
umbe1987

Reputation: 3578

save string to a binary file in python

I would like to know a very basic thing of Python programming as I am a very basic programmer right now): how can I save a result (either a list, a string, or whatever) to a file in Python? I've been searching a lot, but I couldn't find any good answer to this. I was thinking about the ".write ()" method, but (for instance) it seems not working with strings, neither I know what it is supposed to do though. So, my situation is that I have binary fils, which I would like to edit, therefore I found easy to convert them to strings, modify them, and now I'd like to save them i) back to binary files (jpegs images) and ii) in the folder I want. How would I do that? Please I need some help.

UPDATE

Here is the script I'm trying to run:

import os, sys

newpath= r'C:/Users/Umberto/Desktop/temporary'
if not os.path.exists (newpath):
    os.makedirs (newpath)

data= open ('C:/Users/Umberto/Desktop/Prove_Script/Varie/_BR_Browse.001_2065642654_1.BINARY', 'rb+')
edit_data= str (data.read () )
out_dir= os.path.join (newpath, 'feed', 'address')

data.close ()


# do my edits in a secon time...

edit_data.write (newpath)

edit_data.close ()

The error I get is:

AttributeError: 'str' object has no attribute 'write'

UPDATE_2

I tried to use pickle module to serialize my binary file, modify it and save it at the end, but still not getting it to work... This is what I've been trying so far:

import cPickle as pickle
binary= open ('C:\Users\Umberto\Desktop\Prove_Script\Varie\_BR_Browse.001_2065642654_1.BINARY', 'rb')
out= open ('C:\Users\Umberto\Desktop\Prove_Script\Varie\preview.txt', 'wb')
pickle.dump (binary, out, 1)

TypeError                                 Traceback (most recent call last)
<ipython-input-6-981b17a6ad99> in <module>()
----> 1 pprint.pprint (pickle.dump (binary, out, 1))

C:\Python27\ArcGIS10.1\lib\copy_reg.pyc in _reduce_ex(self, proto)
     68     else:
     69         if base is self.__class__:
---> 70             raise TypeError, "can't pickle %s objects" % base.__name__
     71         state = base(self)
     72     args = (self.__class__, base, state)

TypeError: can't pickle file objects

Another thing I didn't get is that if I am supposed to create a file to poit to (in my case I had to create "out", otherwise I wouldn't have the right arguments for the pickle method) or it's not necessary. Hope I'm getting close to the solution.

P.S.: I tried also with pickle.dumps (), not achieving a nicer result though...

Upvotes: 1

Views: 9751

Answers (2)

Diego Herranz
Diego Herranz

Reputation: 2937

If you're opening a binary file and saving another binary file you could do something like this:

with open('file.jpg', 'rb') as jpgFile:
    contents = jpgFile.read()

contents = (some operations here)

with open('file2.jpg', 'wb') as jpgFile:
    jpgFile.write(contents)

Some comments:

  • 'rb' and 'wb' means read and write in binary mode respectively. More info on why 'b' is recommended when working with binary files here.
  • Python's with statement takes care of closing the file when exiting the block.

If you need to save lists, strings or other objects, and retrieving them later, use pickle as others pointed out.

Upvotes: 9

Elephant
Elephant

Reputation: 1344

You can use standard python module named "pickle".

You can read about it here: pickle documentation

Read and write any data structure will be very easy

pickle.dump(obj, file_handler) # for serialize object to file
pickle.load(file)              # for deserialize from file

or you can serialize to string: pickle.dumps(..) and load from it: pickle.loads(...)

Upvotes: 0

Related Questions