0

I've got a program where I receive a file (specifically a SpooledTemporaryFile) and want to preform some editing to it before returning an edited file. However, I am trying to do that processing in a function and I seem to be running into issues with returning a temporary file.

I don't have a need to save the edited file; it should be immediately be sent out to a user. Intuitively, I wanted to do:

# file is a BinaryIO (SpooledTemporaryFile)
process(file)
print(file.read().decode()) # Placeholder for sending data to a user.

def process(file: BinaryIO):
  p_file = SpooledTemporaryFile() # I assume these files (videos) are large, I think I may want to spool them here as well.
  content = file.read()

  p_file.write(contents)
  p_file.write(b"ALSO THIS!")

  return p_file

With this, however, nothing gets printed. The SpooledTemporaryFile is opened with w+b so it should be readable and writable. I assume that p_file is being closed when returned from process and hence it's data is lost. Is there a way for me to either pass this temp file out correctly or another way I can work with these BinaryIO's as desired?

Derek C.
  • 890
  • 8
  • 22
  • `read()` starts at the current location of the file. You're leaving the current location at the _end_. – Charles Duffy Oct 20 '22 at 20:40
  • Change your code to `seek()` back before the beginning before reading. Give me a moment, and I'll find an existing duplicate to close this with... – Charles Duffy Oct 20 '22 at 20:40
  • 1
    You are discarding the return value from `process` – Mikael Öhman Oct 20 '22 at 20:40
  • That too; the second `file.read()` is on the input file that `process()` already did `file.read()` on, making the pointer be at the end. – Charles Duffy Oct 20 '22 at 20:41
  • Had that feeling it was something small like that... Sorry to bother and thanks for your time! Mikael, not in the real program, that's what I get for typing my code on SO and not my editor. – Derek C. Oct 20 '22 at 20:42

0 Answers0