python - 从一个文件写入另一个文件
问题描述
- 以
secret_msg
和路径为参数- 以a+模式打开路径中提到的文件
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)
解决方案
您需要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。
希望有帮助!
推荐阅读
- laravel - 如何在laravel收银员中预览配给?
- git - 如何防止来自 github 的 pip install 添加虚假斜线并失败?
- r - 如何将数据框的元素映射到 R 中的另一个数据框?
- node.js - 在 mono-repo 节点 js 项目上应用 semver
- ruby-on-rails - 验证数组 Active Record 中的包含时出错
- r-markdown - 如何为使用 rmarkdown 创建的 PowerPoint 文件中的图像添加替代文本(用于辅助功能)?
- c++ - O(1) 追加和 O(1) 随机访问数据结构
- javascript - 反应:输入不反映变化
- nginx - 如何为标准和 www 设置 SSL。在 nginx 中使用 Let's Encrypt 的域?
- teradata - 如何从一个非常大的表中获取所有数据?