2

I want to encode a file using uu.encode() method and use the encoded text in the script. For this I have to write that output to a file, by default uu.encode(input_file, output_file) requires the output file name so that it can write the encoded text to that file, then read the file to store in a variable.

But I don't want to do this and store the encoded text directly into a variable. Is it possible?

Here is the typical usage of uu.encode:

import uu
uu.encode("myfile.exe", "encoded_exe.txt")

I tried some stupid moves like this, which took me nowhere.

>>> data = uu.encode("M8510-8681-2015-09-29-220157.flv", sys.stdout.read())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: File not open for reading
>>>

This is not a must-requirement for me, but want to learn a thing or two using this opportunity.

gixxer
  • 814
  • 1
  • 10
  • 25

2 Answers2

4

You can use StringIO to create a file-like object as described in the uu documentation.

import uu

uu.encode("Bar.txt", "Hello.txt")

import StringIO

output = StringIO.StringIO()
uu.encode("Bar.txt", output)
print output.getvalue()
merlin2011
  • 71,677
  • 44
  • 195
  • 329
0

You could try creating a python tempfile. https://docs.python.org/3.4/library/tempfile.html for something more sophisticated. But if you really want to avoid this, you could also try looking at this: virtual file processing in python? for several examples of StringIO and ByteIO.

Community
  • 1
  • 1
mh00h
  • 1,824
  • 3
  • 25
  • 45