"Python" ensures end of file write

Source: Internet
Author: User

Today we have a problem:

When I execute the following code, I find that the file is only half written. That is, when the file size is too large, the following code does not guarantee that the file will be written correctly.

FD = open ('test.txt','w') fd.write ("A Lot of thing") fd.close ()

Workaround:

Source: http://www.crifan.com/python_after_write_file_then_do_not_know_how_long_to_sleep_is_safe_close/

1. In fact, this issue is related to the caching of files, the contents of the caching aspects of the operating system.

For this, the file-level cache already has a corresponding function:

file. Flush ()

Flush the internal buffer, like stdio' s fflush (). This is a no-op on some file-like objects.

Note

Flush () does not necessarily write the file "s data to disk. Use flush ()followed by Os.fsync () to ensure this behavior.

To ensure that the data is written back.

2. And also, as mentioned above, if you want to really make sure that the data is actually written back, you can use:

OS. Fsync (fd)

Force write of the file with FileDescriptor FD to disk. On Unix, this calls the native Fsync () function; On Windows, the MS _commit () function.

If you ' re starting with a Python file object F, first do F.flush (), and then doOs.fsync (F.fileno ()), To ensure the internal buffers associated with F is written to disk.

Availability:unix, and Windows starting in 2.2.3.

So, the relevant, correct, and complete code is:

Import os; fileobj=open ('filename'w'); # write data into fileobj here # First do file flush () Fileobj.flush (); # Then os Fsync () Os.fsync (fileobj); # Then close is safefileobj.close ();

"Python" ensures end of file write

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.