简体   繁体   中英

Python won't write small object to file but will with large object

This is quite confusing. When I have the following code:

lista = [i for i in range(10)]          

file=open("file.txt","a") 
file.write("\n")
file.write("".join(str(lista)))

The output "file.txt" will be an empty file with zero bytes. But when I increase the size of the string to be written ...

lista = [i for i in range(10000)]      # Or larger    

file=open("file.txt","a") 
file.write("\n")
file.write("".join(str(lista)))

It works fine. Although it doesn't make sense to me, it is behaving as if there is a minimum file size for writing to an output file. Why is this? Is this problem unique to my computing environment?

Any help is appreciated. I am working on Mac OS Yosemite. Python 3.

You should invoke the close method after writing something to a file.

lista = [i for i in range(10)]          

file=open("file.txt","a") 
file.write("\n")
file.write("".join(str(lista)))
file.close()

Or use the with statement to close the file automatically:

lista = [i for i in range(10)]          

with open("file.txt","a")  as file:
    file.write("\n")
    file.write("".join(str(lista)))

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