Reputation:
I want to save ''contents'' to a new text file in python. I need to have all the words in lowercase to be able to find the word frequency. '''text.lower()''' didn't work. 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?
Upvotes: 1
Views: 67
Reputation: 20689
You can use file
parameter in print
to directly print the output of print(...)
to your desired file.
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. As you don't have to explicitly use .close
it takes care of that.
Upvotes: 1
Reputation: 13126
You are opening the file page.txt
for reading, but it's not open to write. 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:
# 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
Upvotes: 1
Reputation: 168
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
Upvotes: 0