python - f.write 与打印 >> f

标签 python

在python中写入文件至少有两种方式:

f = open(file, 'w')
f.write(string)

f = open(file, 'w')
print >> f, string     # in python 2
print(string, file=f)  # in python 3

这两者有区别吗?或者还有其他 Pythonic 吗?我正在尝试将一堆 HTML 写入文件,所以我需要通过我的文件编写一堆写/打印语句(但我不需要模板引擎)。

最佳答案

print 做了 file.write 不做的事情,允许您跳过一些基本操作的字符串格式化。

它在参数之间插入空格并附加行终止符。

print "a", "b" # prints something like "a b\n"

它调用对象的__str____repr__特殊方法将其转换为字符串。

print 1 # prints something like "1\n"

如果您使用 file.write 而不是 print,则必须手动执行这些操作。

关于python - f.write 与打印 >> f,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8598228/

相关文章:

python - 如何在Python中使用__slots__转储对象的所有字段

python - 如何在 Tensorflow 中对 3D 特征向量应用线性变换?

python - 如何一次获得所有 Django 外键对象?

python - 如何正确屏蔽 numpy 二维数组?

python - 规范化 Pandas 数据时加速循环

python - 已部署的 Bokeh 服务器显示空白图,但本地一切正常

python - PL/Python 和 postgreSQL : What is the best way to return a table of many columns?

python - 如何将 jupyter notebook 颜色主题融入 vs 代码

python - 在 Python 中,是否可以解压缩字符串列表并将每个字符串中的单个字符放入生成器中?

python - 函数参数提示 Eclipse 与 PyDev