j.taber
j.taber

Reputation: 1

writing output for python not functioning

I am attempting to output a new txt file but it come up blank. I am doing this

my_file = open("something.txt","w")
#and then
my_file.write("hello")

Right after this line it just says 5 and then no text comes up in the file

What am I doing wrong?

Upvotes: 0

Views: 51

Answers (4)

Sakib Ahammed
Sakib Ahammed

Reputation: 2480

The python file writer uses a buffer (BufferedIOBase I think), meaning it collects a certain number of bytes before writing them to disk in bulk. This is done to save overhead when a lot of write operations are performed on a single file. Ref @m00am

Your code is also okk. Just add a statement for close file, then work correctly.

my_file = open("fin.txt","w")
#and then
my_file.write("hello")
my_file.close()

Upvotes: 0

m00am
m00am

Reputation: 6298

As Two-Bit Alchemist pointed out, the file has to be closed. The python file writer uses a buffer (BufferedIOBase I think), meaning it collects a certain number of bytes before writing them to disk in bulk. This is done to save overhead when a lot of write operations are performed on a single file.

Also: When working with files, try using a with-environment to make sure your file is closed after you are done writing/reading:

with open("somefile.txt", "w") as myfile:
    myfile.write("42")

# when you reach this point, i.e. leave the with-environment,
# the file is closed automatically.

Upvotes: 1

Samuel
Samuel

Reputation: 3801

If you don't want to care about closing file, use with:

with open("something.txt","w") as f: 
    f.write('hello')

Then python will take care of closing the file for you automatically.

Upvotes: 1

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18467

You must close the file before the write is flushed. If I open an interpreter and then enter:

my_file = open('something.txt', 'w')
my_file.write('hello')

and then open the file in a text program, there is no text.

If I then issue:

my_file.close()

Voila! Text!

If you just want to flush once and keep writing, you can do that too:

my_file.flush()
my_file.write('\nhello again')  # file still says 'hello'
my_file.flush()   # now it says 'hello again' on the next line

By the way, if you happen to read the beautiful, wonderful documentation for file.write, which is only 2 lines long, you would have your answer (emphasis mine):

Write a string to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.

Upvotes: 1

Related Questions