Py学习  »  Python

从其他/Program python调用函数

pythoncoder • 5 年前 • 1631 次点击  

`第一个程序: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

第二个程序:Second.py

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

for line in input_file:
    if "ef" in line:
       print(line)

预期产量:

英孚

得到输出:

英孚

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

编辑:应用的代码块

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51543
 
1631 次点击  
文章 [ 2 ]  |  最新文章 5 年前
hygull
Reply   •   1 楼
hygull    6 年前

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

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

list=["ab","cd","ef"]

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

现在你会得到你所期望的。现在 输入文件 会有以下不同于你的情况。

ab
cd
ef

注: 但如果你愿意的话 第一个.py 第二次,它将继续添加为 a+ 如果文件不存在,则创建文件,否则将追加文件。 为了更好地处理此代码,请使用 操作系统路径 模块的 exists() 功能。

如果你想调用 第一个.py 然后将其包装在函数中。然后将该函数导入 second.py 打电话来。

例如

首先确保 第一个.py 第二年 在同一个目录中。

第一个.py

def create_file(file_name):
    list=["ab","cd","ef"]
    for i in list:
        with open(file_name, "a+") as input_file:
            print(" {}".format(i), file = input_file)

第二年

from first import create_file

def read_file(file_name):
    # Create file with content
    create_file(file_name)

    # Now read file content
    input_file = open(file_name, 'r')     
    for line in input_file:
        if "ef" in line:
           print(line)

read_file('input.txt')

打开终端,导航到此目录,运行 python second.py .

https://www.learnpython.org/en/Module... | https://www.digitalocean.com... | https://www.programiz.com/pytho... 如果你想阅读并尝试 如何创建模块/包 在巨蟒中。

更新 :上面有一个问题,正如您在comment中提到的,在每次运行时,它都会附加内容。我们把它改一下 第一个.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)

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

blhsing
Reply   •   2 楼
blhsing    6 年前

你正在打开一个 for 循环,和 w 作为 open 它的功能 打开 覆盖它打开的文件,这就是为什么只从循环的最后一次迭代中获取输出。

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

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