如何使用第三个python文件组合两个python文件,第三个python文件还可以向同一个文件添加一些代码?

2024-03-28 14:30:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个python文件,我想做一个程序,可以合并这些文件,并显示我的新文件。你知道吗

文件1

def functiona(a):
    print("hi")

文件2

def functionb(a):
    print("hi")

组合文件

def function(a):
    print("hi")

def functionb(a):
    print("hi")

if __name__ = "__main__":
    functiona(4)
    functionb(5)

Tags: 文件name程序ifmaindeffunctionhi
1条回答
网友
1楼 · 发布于 2024-03-28 14:30:55

更新: 将其放入一个文件中,并从控制台使用它来组合函数并将它们输出到一个文件中。你知道吗

# arg 0: The path where the combined file will be created.
# args 1..inf: Paths to the files where your functions found.

import sys

with open(sys.argv[1], "w") as out_file:
    for i in range(2, len(sys.argv)):
        with open(sys.argv[i]) as in_file:
            for l in in_file.readlines():
                out_file.writelines(l)
            out_file.writelines("\n\n")

    # What ever you need to add at the end"
    additional_text = 'if __name__ = "__main__":\n\tfunctiona(4)\n\tfunctionb(5)'
    out_file.writelines(additional_text)

相关问题 更多 >