0

For my project, I need to be able to store random byte strings in a file and read the byte string again later. For example, I want to store randomByteString from the following code:

>>> from os import urandom 
>>> randomByteString=urandom(8)
>>> randomByteString
b'zOZ\x84\xfb\xceM~'

What would be the proper way to do this?

Edit: Forgot to mention that I also want to store 'normal' string alongside the byte strings.

4
  • 2
    1. open the file, 2. write, 3. ???, 4. Profit Commented Apr 20, 2013 at 4:10
  • What else are you storing in the file? Is it binary or text? Commented Apr 20, 2013 at 4:13
  • Oh right! Forgot that I can open the file in binary mode! I also wish to store some text in this file. Would it be okay to open in binary mode and write to it then open in normal mode and write to it? From my tests, it seems to work but maybe there's something I missed. Commented Apr 20, 2013 at 4:19
  • @Kevin Yes, it is fine to open the file in binary mode and write text. In fact, not all platforms treat binary and text files differently, when they do, the only difference is in the handling of newlines Commented Apr 20, 2013 at 4:55

2 Answers 2

3

Code like:

 >>> fh = open("e:\\test","wb")
 >>> fh.write(randomByteString)
 8
 >>> fh.close()

Operate the file as binary mode. Also, you could do it in a better manner if the file operations are near one place (Thanks to @Blender):

>>> with open("e:\\test","wb") as fh:
        fh.write(randomByteString)

Update: if you want to strong normal strings, you could encode it and then write it like:

 >>> "test".encode()
 b'test'
 >>> fh.write("test".encode())

Here the fh means the same file handle opened previously.

Sign up to request clarification or add additional context in comments.

3 Comments

I'd use a context manager instead: with open(...) as handle:
@Blender OK. I will update the coding as your suggestions. Thanks!
@Kevin It also could write normal strings. See the update part please.
0

Works just fine. You can't expect the output to make much sense though.

>>> import os
>>> with open("foo.txt", "wb") as fh:
...     fh.write(os.urandom(8))
...
>>> fh.close()
>>> with open("foo.txt", "r") as fh:
...     for line in fh.read():
...         print line
...
^J^JM-/
^O
R
M-9
J
~G

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.