简体   繁体   English

Python:跨模块写入相同的文件?

[英]Python: Writing to the same file across modules?

EDIT 3: Decided not to use the write method inside the module2.function. 编辑3:决定不在module2.function中使用write方法。 i just passed the things i wanted written out to variables in module1, and then used the write method there. 我只是将我想写的东西传递给module1中的变量,然后在那里使用了write方法。 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: 编辑2:所以现在我有跨模块的写操作,除了函数显示优先于module1代码:

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). 感谢您回答旧问题:传递f - > module2.function1(f)。

Say I have a main script in module1: 假设我在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. 所以,我正在使用从module2加载的函数。 say that function1(), from module2, contains this code: 假设来自module2的function1()包含以下代码:

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

How would I avoid a NameError: global name f is not defined. 如何避免NameError:未定义全局名称f。 ie its not recognizing that I already told it which file to write to earlier in module1. 即它没有意识到我已经告诉它早先在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. 我希望能够在module1中创建文件,然后重复使用module1中module2的函数,同时总是在这些函数中使用f.write()短手引用相同的文件。

Any ideas? 有任何想法吗? Thank you. 谢谢。

You can pass the file object to function1() . 您可以将文件对象传递给function1()

But the file with pointer f will be closed after the execution of with block. 但是执行with block后,指针f的文件将被关闭。 So calling module2.function1() after with block won't work. 因此在with block之后调用module2.function1()将不起作用。

PS: Before posting this answer, I failed to realize that @falsetru has already posted the answer in comment. PS:在发布这个答案之前,我没有意识到@falsetru已经在评论中发布了答案。

module 1---------------------- 模块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---------------------- 模块2 ----------------------

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM