Trying to copy a openstring onto a txt file

This is the place for queries that don't fit in any of the other categories.

Trying to copy a openstring onto a txt file

Postby Hissing Cockroach » Sun Nov 24, 2013 2:09 am

Hi. I am trying to copy a string onto a txt file. I've looked up answers, but
only found ones that didn't work.
What I've tried is:

Code: Select all
import pygame
x = "text"
pygame.text.save(x,"Output.txt")


Code: Select all
import pygame
x = "text"
pygame.str.save(x,"Output.txt")


and

Code: Select all
text_file = open("Output.txt", "w")
text_file.write("text")
text_file.close()


none of these returned errors, but none of
them printed anything onto the txt file.
Can anyone help with this?
User avatar
Hissing Cockroach
 
Posts: 108
Joined: Sat Sep 14, 2013 2:35 pm
Location: Earth

Re: Trying to copy a openstring onto a txt file

Postby Mekire » Sun Nov 24, 2013 2:25 am

Um... the first one...
Not sure why you are trying to use pygame. It has nothing to do with this.

The second one...
This does indeed create a file called Output.txt and writes the word "text" to it.
What's the problem exactly?

-Mek
User avatar
Mekire
 
Posts: 984
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Trying to copy a openstring onto a txt file

Postby Hissing Cockroach » Sun Nov 24, 2013 2:51 am

My problem is that it does not write "text" to it. It
simply creates a blank txt file.
User avatar
Hissing Cockroach
 
Posts: 108
Joined: Sat Sep 14, 2013 2:35 pm
Location: Earth

Re: Trying to copy a openstring onto a txt file

Postby Hissing Cockroach » Sun Nov 24, 2013 2:54 am

Oh, wait - This DOES work. Sorry.
User avatar
Hissing Cockroach
 
Posts: 108
Joined: Sat Sep 14, 2013 2:35 pm
Location: Earth

Re: Trying to copy a openstring onto a txt file

Postby Kebap » Wed Nov 27, 2013 11:48 am

Hissing Cockroach wrote:
Code: Select all
text_file = open("Output.txt", "w")
text_file.write("text")
text_file.close()

Can anyone help with this?

This will definitely work. Even better though:
Code: Select all
with open("Output.txt", "w") as text_file:
    text_file.write("text")

This way, you can't forget to close() the file. As soon as the block ends, the file is closed automagically. :mrgreen:
Learn: How To Ask Questions The Smart Way
Join the #python-forum IRC channel on irc.freenode.net and chat with uns directly!
Kebap
 
Posts: 366
Joined: Thu Apr 04, 2013 1:17 pm
Location: Germany, Europe


Return to General Coding Help

Who is online

Users browsing this forum: micseydel and 2 guests