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