python - 将字符串写入文件的 pythonic 方式是什么?

标签 python file-io

使用 File.write()print>>File, 有什么区别?

写入文件的 pythonic 方式是什么?

>>> with open('out.txt','w') as fout:
...     fout.write('foo bar')
... 

>>> with open('out.txt', 'w') as fout:
...     print>>fout, 'foo bar'
... 

使用 print>>File, 有优势吗?

最佳答案

write() 方法写入缓冲区,每当溢出/文件关闭/收到显式请求时,缓冲区(缓冲区)就会刷新到文件中(.flush() ).

print 将阻止执行,直到实际写入文件完成。

首选第一种形式,因为它的执行效率更高。此外,第二种形式是丑陋的和非 pythonic 的。

关于python - 将字符串写入文件的 pythonic 方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20868484/

相关文章:

c++后端使用swig wrapper调用python级别定义的回调

python - 将字符串每一行中的第一个单词存储到列表中

Java读取文本文件中的不同数组

c - 将文本文件读取到链表数组时出现段错误

matlab - matlab中的load命令加载空白文件

Python:从 python 可执行文件读取/写入文件时出错

python - 在 python 中使用多处理优化大数组的处理

python - 如何在 Databricks 笔记本中获取运行参数和 runId?

python - 如何修复 "AttributeError: ' str'对象没有属性 'items'“

c - 从文件中读取一行并将其存储在 C 中的字符串数组中