繁体   English   中英

Append 文件内容到另一个文件使用 Python

[英]Append File Content to Another File using Python

我有一个包含特定代码的文件 sample.py。 在 sample.py 中有一些函数需要执行。 在执行这些功能之后。 我想将所有内容从 sample.py 复制到 temp.py。 我怎样才能做到这一点?

尝试这个:

sample.py中:

##### Your functions
def func1(): # Example
    print("Something")

# ...
    
def main():
    ##### Execute functions
    func1() # Example
    
    # ...



    ##### Copy file

    data = ""

    with open("sample.py", "r") as f:
        data = f.read() # Read contents of 'sample.py'


接下来,添加以下块之一

覆盖“temp.py”:

    with open("temp.py", "w") as f:
        f.write(data)

添加到(附加)“temp.py”的末尾:

    with open("temp.py", "a") as f:
        f.write(data)

然后加

if __name__ == "__main__":
    main()

暂无
暂无

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

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