Python 2.7:打印到文件 [英] Python 2.7: Print to File

查看:224
本文介绍了Python 2.7:打印到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要直接打印到文件而不是 sys.stdout 会产生以下语法错误:

Why does trying to print directly to a file instead of sys.stdout produce the following syntax error:

Python 2.7.2+ (default, Oct  4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f1=open('./testfile', 'w+')
>>> print('This is a test', file=f1)
  File "<stdin>", line 1
    print('This is a test', file=f1)
                            ^
SyntaxError: invalid syntax

从帮助(__ builtins__)我有以下信息:

From help(__builtins__) I have the following info:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.

那么更改标准流打印的正确语法会写到?

So what would be the right syntax to change the standard stream print writes to?

我知道有不同的可能更好的方式写入文件,但我真的不明白为什么这应该是一个语法错误...

I know that there are different maybe better ways to write to file but I really don't get why this should be a syntax error...

一个很好的解释将不胜感激!

A nice explanation would be appreciated!

推荐答案

如果你想使用打印函数在Python 2中,您必须从 __未来__ 导入:

If you want to use the print function in Python 2, you have to import from __future__:

from __future__ import print_function

但是您可以在不使用该功能的情况下具有相同的效果也是:

But you can have the same effect without using the function, too:

print >>f1, 'This is a test'

这篇关于Python 2.7:打印到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆