简体   繁体   中英

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?

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.

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.

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM