【问题标题】:how to direct output into a txt file in python in windows如何在Windows中的python中将输出定向到txt文件
【发布时间】:2011-06-17 06:22:01
【问题描述】:
import itertools  

variations = itertools.product('abc', repeat=3)  
for variations in variations:  
    variation_string = ""  
    for letter in variations:  
        variation_string += letter  
    print (variation_string)  

如何将输出重定向到 txt 文件(在 windows 平台上)?

【问题讨论】:

  • 第 1 步是正确格式化您的代码。请使用{} 按钮。
  • @S.Lott 为什么?这没有任何意义

标签: python


【解决方案1】:

从控制台你会写:

python script.py > out.txt

如果你想用 Python 来做,那么你会写:

with open('out.txt', 'w') as f:
    f.write(something)

显然这只是一个简单的例子。你显然会在 with 块内做更多的事情。

【讨论】:

    【解决方案2】:

    在窗口命令提示符下,该命令会将program.py的输出存储到文件output.txt中

    python program.py > output.txt
    

    【讨论】:

    • 上述程序的输出就像一个集群状态::aaaaabaacabaabbabcacaacbaccbaabbabbacbbabbbbbcbcabcbbcccaacabcaccbacbbcbcccaccbccc////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////先生输出的行是 aaa,下一行是 aab,下一行是 aac,依此类推......谢谢
    【解决方案3】:

    如果是我,我会使用上面 David Heffernan 的方法将变量写入文本文件(因为其他方法需要用户使用命令提示符)。

    import itertools  
    
    file = open('out.txt', 'w')
    variations = itertools.product('abc', repeat=3)  
    for variations in variations:  
        variation_string = ""  
        for letter in variations:  
            variation_string += letter  
        file.write(variation_string)
    file.close()
    

    【讨论】:

      【解决方案4】:

      你可以使用>>

      log = open("test.log","w")
      
      print >> log, variation_string
      
      log.close()
      

      【讨论】:

      • import itertools file = open('out.txt', 'w') changes = itertools.product('abc', repeat=3) 用于变体中的变体:variation_string = "" 用于输入字母变体:variation_string += letter file.write(variation_string) file.close() 上面程序的输出就像一个集群状态 ::aaaaabaacabaabbabcacaacbaccbaabbabacbbabbbbbbcbcabcbb//////先生你能修改程序以便输出是在一行接一行中,输出的第一行是 aaa,下一行是 aab,下一行是 aac,依此类推..谢谢
      【解决方案5】:

      您也可以直接在脚本中将stdout 重定向到您的文件,因为print 默认写入sys.stdout 文件处理程序。 Python 提供了一种简单的方法:

      import sys  # Need to have acces to sys.stdout
      fd = open('foo.txt','w') # open the result file in write mode
      old_stdout = sys.stdout   # store the default system handler to be able to restore it
      sys.stdout = fd # Now your file is used by print as destination 
      print 'bar' # 'bar' is added to your file
      sys.stdout=old_stdout # here we restore the default behavior
      print 'foorbar' # this is printed on the console
      fd.close() # to not forget to close your file
      

      【讨论】:

      【解决方案6】:

      扩展至David's answer

      如果您使用的是 PyCharm,

      转到运行 --> 编辑配置 --> 日志 --> 勾选保存控制台 输出到文件 --> 输入完整路径 --> 应用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-05
        • 1970-01-01
        • 2016-08-02
        • 1970-01-01
        • 2010-10-27
        • 1970-01-01
        相关资源
        最近更新 更多