Question

EDIT 3: Decided not to use the write method inside the module2.function. i just passed the things i wanted written out to variables in module1, and then used the write method there. much easier, and they write in order now. thanks again everyone.

EDIT 2: So now I have the writes across modules working, except that the functions are displaying priority over the module1 code:

f.write("bob")
module2.otherfunctionthatwrites(f)
module2.otherfunctionthatwrites(f)
f.write("bob")

writes in this order:

writtenfrommodule2function
writtenfrommodule2function
bob
bob

instead of this order:

bob
writtenfrommodule2function
writtenfrommodule2function
bob

any idea what could be going on?


Thank you for answering the old question: pass f --> module2.function1(f).

Say I have a main script in module1:

import module2

filename = raw_input("What would you like to name the output file?: ")
with open(str(filename + ".txt"), "w") as f:
    f.write("Test2")

module2.function1()

So, I am using a function that was loaded from module2. say that function1(), from module2, contains this code:

def function1():
    f.write("Test 3")

How would I avoid a NameError: global name f is not defined. ie its not recognizing that I already told it which file to write to earlier in module1. I'd like to be able to create the file in module1, and yet repeatedly use functions from module2 in module1, while always referring to the same file with the f.write() short hand inside those functions.

Any ideas? Thank you.

Was it helpful?

Solution

You can pass the file object to function1().

But the file with pointer f will be closed after the execution of with block. So calling module2.function1() after with block won't work.

P.S.: Before posting this answer, I failed to realize that @falsetru has already posted the answer in comment.

OTHER TIPS

module 1----------------------

import module2

filename = raw_input("What would you like to name the output file?: ")
with open(str(filename + ".txt"), "w") as f:
    f.write("Test2")
    module2.function1(f)

module 2----------------------

def function1(f):
    f.write("Test 3")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top