Python 从其他/程序调用函数

Python 从其他/程序调用函数,python,python-3.x,function,call,func,Python,Python 3.x,Function,Call,Func,`第一个程序:First.py list=["ab","cd","ef"] for i in list: with open("input.txt", "w") as input_file: print(" {}".format(i), file = input_file) 预期产出: ab cd ef ef 但我得到了输出: ef 第二个程序:Second.py input_file = open('input.txt','r') for line

`第一个程序:First.py

list=["ab","cd","ef"]
for i in list:
    with open("input.txt", "w") as input_file:
        print(" {}".format(i), file = input_file)
预期产出:

ab
cd
ef
ef
但我得到了输出:

ef
第二个程序:Second.py

input_file = open('input.txt','r')     

for line in input_file:
    if "ef" in line:
       print(line)
预期产出:

ab
cd
ef
ef
得到输出:

ef
现在我想直接从first.py调用文本文件(input.txt),并在second.py中使用它?`如何从其他python程序调用函数


编辑:应用代码块

您正在为循环打开文件,并使用
w
作为
open
函数的模式参数,它使
open
覆盖它打开的文件,这就是为什么您只获得循环最后一次迭代的输出

您应该在循环之外打开文件:

with open("input.txt", "w") as input_file:
    for i in list:
        print("{}".format(i), file = input_file)

first.py
中,像这样更改代码

w
模式用于写入操作。在for循环的每次迭代中,您将覆盖最后一个内容并编写新内容。因此,
input.txt
中有
ef
(最后)

现在你将从中得到你所期望的。现在,
input.txt
将具有与您的案例不同的以下内容

ab
cd
ef
注意:但如果您将第一次运行
.py
第二次,它将继续添加为
a+
创建文件(如果文件不存在),否则会追加。 为了更好地使用此代码,请使用操作系统路径模块的
exists()
函数

如果要调用
first.py中可用的代码,请将其包装到函数中。然后在
second.py
中导入该函数并调用

比如说

首先确保
First.py
second.py
位于同一目录中

第一,派克

二等兵

input_file = open('input.txt','r')     

for line in input_file:
    if "ef" in line:
       print(line)
打开终端,导航到此目录,运行
python second.py

如果您想阅读并尝试如何用Python创建模块/包,那么| |将为您提供帮助

更新:正如您在评论中提到的,上面的问题是,在每次运行中,它都会附加内容。让我们对
first.py做一点修改来修复它,如下所示


就是这样(如果您被卡住,请在评论中更新)。

Hi!请使用编辑器对代码进行格式化,使其可读。我更改了格式
list
是python中的保留字。当你给它赋值时,你就失去了这个词的所有功能。基本上,如果您尝试调用
list(something)
,您将得到
TypeError
。不要使用关键字或保留字作为变量名!谢谢。还有一个问题,如何直接调用second.py程序的input.txt文件,而不是像这样调用-->input\u file=open('input.txt','r')如何在second.py中导入该函数并调用请给我一个解决方案。我已经更新了我的答案,请检查,很抱歉我很晚才回答您的问题。非常感谢。当我第一次运行代码时,我得到了正确的输出,但当我再次运行时,它会打印两次答案,然后再次运行代码,它会打印三次..我不知道为什么请建议我好的,我得到了。你的意思是在每次跑步中,你只需要相同的o/p。做一件事,检查文件是否存在。如果存在,请将其删除并重新创建。因此,在一次运行中,只有列表的内容会写入文件。在第二个会话中,程序将检测到存在并删除它。同样,它将创建与以前相同的内容。检查一下,我已经更新了我的答案。我也保留了我的旧版本,以便您能够正确理解其中的差异。对于使用
list
作为变量没有任何评论?非常感谢。还有一个问题,如何在second.py中导入该函数并调用请给我一个解决方案。
import os

def create_file(file_name):
    l = ["ab", "cd", "ef"]

    if os.path.exists(file_name): # If file `input.txt` exists (for this example)
        os.remove(file_name)      # Delete the file

    for i in l:
        with open(file_name, "a+") as input_file:
            print(" {}".format(i), file = input_file)