简体   繁体   English

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

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

I want to save ''contents'' to a new text file in python.我想将“内容”保存到 python 中的新文本文件中。 I need to have all the words in lowercase to be able to find the word frequency.我需要将所有单词都设为小写才能找到词频。 '''text.lower()''' didn't work. '''text.lower()''' 不起作用。 Here is the code;这是代码;

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

I want to save the results of print to a new text file.我想将打印结果保存到一个新的文本文件中。 How can I do that?我怎样才能做到这一点?

You are opening the file page.txt for reading, but it's not open to write.您正在打开文件page.txt进行阅读,但未打开进行写入。 Since you want to save to a new text file, you might also open new_page.txt where you write all of the lines in page.txt lowercased:既然你要保存到一个新的文本文件,你可能同时开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())

The important thing to note is that the with statement negates the need for you to close the file, even in the case of an error需要注意的重要一点是with语句不需要您关闭文件,即使在出现错误的情况下

You can use file parameter in print to directly print the output of print(...) to your desired file.您可以在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()

Note: Use with while operating on files.注意:在对文件进行操作时使用with As you don't have to explicitly use .close it takes care of that.由于您不必明确使用.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