【问题标题】:Append File Content to Another File using Python使用 Python 将文件内容附加到另一个文件
【发布时间】:2020-11-01 12:14:14
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x file file-management


    【解决方案1】:

    试试这个:

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-03
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 2013-11-09
      • 2016-03-30
      相关资源
      最近更新 更多