【问题标题】:Redirect print output to file in Python将打印输出重定向到 Python 中的文件
【发布时间】:2015-01-29 20:15:47
【问题描述】:

我正在尝试将打印输出重定向到 Python 3.4 中的文件 - 现在我的脚本打印到 shell。我真的不需要它来做到这一点。这是我的代码:

with open('Input.txt') as namelist:
    for line in namelist:
        line_lower = line.lower()
        a = namelist.readline()
        if fuzz.ratio(a, line) >= 95:
            print(fuzz.ratio(a, line))
            print(a + ": " + line)

我真的很想打印出来的结果:

            print(fuzz.ratio(a, line))
            print(a + ": " + line)

输出到文本文件。

到目前为止,我发现它似乎不适用于 Python 3,因为 print 语句现在是需要括号而不是语句的函数。下面是一个不起作用的例子:

f = open('out.txt', 'w')
print >> f, 'Filename:', filename  # or f.write('...\n')
f.close()

来自: How to redirect 'print' output to a file using python?

【问题讨论】:

  • 从交互式提示中尝试help(print),它会告诉您有关file 参数的所有信息。

标签: python file printing output


【解决方案1】:

Python 3.0 引入了支持可选参数fileprint() 函数。所以你可以做类似的事情

with open("myfile.txt", "w") as f:
    print("Hello, world!", file=f)

更多信息here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 2012-06-22
    • 2011-11-01
    • 2016-08-02
    • 2011-05-05
    • 1970-01-01
    相关资源
    最近更新 更多