Search code examples
pythonfile-iopython-module

Multiple File Stream Issue


In my project, I am using 3 files throughout the whole process. The source file (.ada), a "three address code" file (.TAC), and my own temporary file for use during processing (.TACTMP).

in Caller.py:

TACFILE = open(str(sys.argv[1])[:-4] + ".TAC", 'w') # line 17
# Does a bunch of stuff
TACFILE.close() # line 653
# the below function is imported from Called.py
post_process_file_handler() # line 654

in Called.py:

TAC_FILE_NAME = str(sys.argv[1])[:-4] # line 6
TAC_lines = open(TAC_FILE_NAME + ".TAC", 'r').readlines() # line 7

If I try to run my program without already having a (even if it's blank) .TAC file, I will get the following error:

Traceback (most recent call last):
  File "Caller.py", line 8, in <module>
    from Called import post_process_file_handler
  File "Called.py", line 7, in <module>
    TAC_lines = file(TAC_FILE_NAME + ".TAC", 'r').readlines()
IOError: [Errno 2] No such file or directory: 'test76.TAC'

Why would this be happening? This error is being thrown even if I put a breakpoint at the beginning of Caller.py, well before the post_process_file_handler() function ever gets called.

For clarity: test76.TAC should be being generated by Caller.py, and then Called.py should open that file to process it further, for some reason that isn't happening.


Solution

  • This may be specific to my case, but I found out the issue is due to the order and manner in which I was using these streams.

    In short, when the import line was encountered:

    from Called import post_process_file_handler
    

    it triggered some sort of initialization, and since the file pointer was a global variable in Called.py, it was initialized before Caller.py had a chance to create the .TAC file it would read from.

    Moving the import line to just before I use the function fixed my issue, as nothing in Called.py is initialized until after Caller.py is done doing its work.