Skip to content
Sign upLog in
← Back to Community

Python not writing to file

Profile icon
LordTopley

So, I'm learning from scratch and I've just begun with Writing to files.

Here is my code:

my_file = open('out.txt', 'w')
my_file.write('Hello World')

I see the out.txt is created, but nothing is written to the file

Voters
Profile icon
johmon6
Profile icon
LordTopley
Comments
hotnewtop
Profile icon
LordTopley

I worked it out.

I was forgetting to the close() the file after writing.

For those finding the same issue, this is the corrected code

my_file = open('out.txt', 'w')
my_file.write('Hello World')
my_file.close()

Profile icon
AbuAlAsif1

Thanks

@LordTopley
, I was having the exact same problem.

Profile icon
gozie11

@LordTopley
I was having the same problem just because i forgot the parentheses at the end of file.close()

Profile icon
DanielTerner

A very good question. In college, I was given homework and I had the same problem. If you haven't found a solution, I recommend taking a look at Mercurynews, there's a lot of useful information. I think everyone has difficult problems at university, it's very good that finding a solution has become easier these days. So every problem is solved in minutes.

Profile icon
gorgeliee

Just read about this topic Python not writing to file here if you are interested into technical stuff for now. All of you will be able to find more on https://www.dissertation-service.org/ as through it we will be able to find what this was all about and share it with the rest of the community that needs it,

Profile icon
wolfieboy09

You can do

file = open('aFile.txt', 'w') file.write('stuff') file.close

and it will write what you want. (I know there has been a answer already, and i just wanted to help.) And you do need to close the file with file.close()