creating a txt file using a variable in python

betty from

I'm working on a program for school that asks the user what they would like to name a file and then I'm supposed to write to that file.

So far I have this:

dream_file = input("What file name would you like to save the cards? ")
dream_file = open(dream_file, 'w')



When I run it I get this error: <_io.TextIOWrapper name='dream' mode='w' encoding='US-ASCII'>

And as far as I know the file never gets created.

python file


answered 6 days ago a625993 #1

That's not an error. An error would come with a clear error message and it would have a stack trace, along with lines of code and whatnot. I think that what you have here is what comes out when you do


That statement doesn't print the file contents. In fact, it can't, because you're opening the file in write mode. Instead, it prints the string representation of the dream_file, which is an object of type _io.TextIOWrapper. If you want to print the string you just put into the file, you can instead do


Try looking for the new file in the folder your code is located in, or exploring the input and output functionality of python to get a better understanding of how it works.

answered 6 days ago Jax Briggs #2

your file was created by using the 'w' in the open function , and " <_io.TextIOWrapper name='dream' mode='w' encoding='US-ASCII'> " comes from print(dream_file) wich means dream_file is a _io.textIOWrapper Object.

check the directory in that your python is, you should find a file named as you input and with dream_hand1 data inside.

answered 6 days ago Evan #3

A file is definitely being written, but as others have mentioned you are simply printing out the string representation of the file handle's python representation. If you want to print the file contents, you only need to make a couple changes.

# it is poor practice to reuse variable names
# for completely different things. It is best
# to differentiate your file path and the file
# handler itself.
dream_file_path = input("What file name would you like to save the cards? ")

# w+ allows reading and writing of files
dream_file = open(dream_file_path, 'w+')


# seek 0 brings you back from where you just
# wrote (end of the file), to the beginning

# .read() simply reads the entire file as a string