首页 > 解决方案 > 从一个文件写入另一个文件

问题描述

  1. secret_msg和路径为参数
    1. 以a+模式打开路径中提到的文件
    2. secret_msg在上面打开的文件中写入 的内容。我该怎么做呢 ?它说错误

'str' 对象没有属性 'write' 4. 关闭文件

返回:该函数没有返回参数

message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2]
final_path= user_data_dir + '/secret_message.txt'

#Code starts here
secret_msg = " ".join(message_parts)
def write_file(secret_msg, path) :
    open("path" , 'a+' )
    path.write(secret_msg)
    path.close()

write_file(secret_msg,final_path)

print(secret_msg)

标签: pythonfile-handling

解决方案


您需要open该文件,然后调用该write方法。

这里有一种方法:

def write_file(secret_msg, path):
    f = open(path, 'a+')
    f.write(secret_msg)
    f.close()

或使用with

def write_file(secret_msg, path):
    with open(path, 'a+') as f:
        f.write(secret_msg)

我建议你看看How to write a file with Python

希望有帮助!


推荐阅读