【问题标题】:What is the pythonic way to write strings to file?将字符串写入文件的pythonic方法是什么?
【发布时间】:2014-01-19 01:07:56
【问题描述】:

使用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,有优势吗?

【问题讨论】:

  • 我认为是第一个。显式优于隐式。
  • 同意。第二个主要是让 C 开发人员有宾至如归的感觉。
  • 在python3中,第二个是print('foo bar', file=fout),但第一个保持不变。
  • 你应该看看 here 以获得正确的解释顺便说一句
  • 这些做不同的事情。即使您在打印语句的末尾加上逗号,软空格功能也会毁了您的一天。

标签: python file-io


【解决方案1】:

最 Pythonic 的方式是 .write()。

我什至不知道其他方式,但它甚至不适用于 Python 3.3

类似的做法是:

fout = open("out.txt", "w")
fout.write("foo bar")
#fout.close() if you were done with the writing

【讨论】:

  • Python 3 将print 改为函数,所以语法不同:print("some string", file=fout)
【解决方案2】:

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

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

首选第一种形式,因为它的执行效率更高。此外,第二种形式丑陋且不符合pythonic。

【讨论】:

    猜你喜欢
    • 2011-04-10
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2011-03-25
    • 2011-06-28
    • 1970-01-01
    相关资源
    最近更新 更多