繁体   English   中英

将打印函数的输出写入文本文件

[英]writing the output of print function to a textfile

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

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

我想将打印结果保存到一个新的文本文件中。 我怎样才能做到这一点?

您正在打开文件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语句不需要您关闭文件,即使在出现错误的情况下

您可以在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因此它会照顾到这一点。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM