【问题标题】:writing the output of print function to a textfile将 print 函数的输出写入文本文件
【发布时间】:2020-07-03 13:37:39
【问题描述】:

我想在 python 中将“内容”保存到一个新的文本文件中。我需要将所有单词都小写才能找到单词频率。 '''text.lower()''' 没有用。这是代码;

text=open('page.txt', encoding='utf8')
for x in text:
print(x.lower())

我想将打印结果保存到一个新的文本文件中。我该怎么做?

【问题讨论】:

    标签: python python-3.x file save file-handling


    【解决方案1】:

    您可以使用print中的file参数将print(...)的输出直接打印到您想要的文件中。

    text=open('page.txt', encoding='utf8')
    text1=open('page1.txt', mode='x',encoding='utf8') #New text file name it according to you
    for x in text:
        print(x.lower(),file=text1)
    text.close()
    text1.close()
    

    注意:操作文件时使用with。由于您不必显式使用 .close,它会处理这些问题。

    【讨论】:

      【解决方案2】:

      您正在打开文件page.txt 进行读取,但未打开以进行写入。由于您想保存到一个新的文本文件,您还可以打开new_page.txt,在其中将page.txt 中的所有行都写成小写:

      
      # the with statement is the more pythonic way to open a file
      with open('page.txt') as fh:
      
          # open the new file handle in write mode ('w' is for write, 
          # it defaults to 'r' for read
          with open('new_page.txt', 'w') as outfile:
              for line in fh:
                  # write the lowercased version of each line to the new file
                  outfile.write(line.lower())
      

      需要注意的重要一点是,with 语句不需要您关闭文件,即使在出现错误的情况下也是如此

      【讨论】:

        【解决方案3】:
        import sys 
        stdoutOrigin=sys.stdout 
        sys.stdout = open("yourfilename.txt", "w")
        #Do whatever you need to write on the file here.
        sys.stdout.close()
        sys.stdout=stdoutOrigin
        

        【讨论】:

        • 请不要只发布代码作为答案,还要说明您的代码的作用以及它如何解决问题的问题。带有解释的答案通常质量更高,更有可能吸引投票。
        • 虽然这篇文章可能会回答这个问题,但仅代码的答案通常被认为是低质量的。请提供一些理由/文字解释,说明为什么这是正确答案,即使很短。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-13
        • 2015-01-21
        相关资源
        最近更新 更多