Opening a file to add

I only had a shrewd thought, and I thought it was better to ask here right here. Out of curiosity, does anyone know whether to open a file for addition, for example:

file_name = "abc" file_handle = open(file_name,"a") 

In essence, this is the same as opening a file for writing and searching to the end:

 file_name = "abc" file_handle = open(file_name,"w") file_handle.seek(0,2) # 0 for offset, 2 for end-of-file 

I'm just wondering if opening the file for append essentially makes the second block open for writing, followed by a search to the end of the file, behind the scenes.

+6
source share
4 answers

After I played a little in my terminal, I can tell what differences are on ubuntu linux 11.04 using python 2.7.1.

Opening with "w" truncates (ie deletes the contents) of the file immediately after opening it. In other words, by simply opening the file with open('file.txt', 'w') and going beyond the blank sheet.

Opening with 'a' leaves the contents of the file intact. Thus, opening with open('file.txt', 'a') and exiting leaves the file unchanged.

This also applies to update options for open. The open('file.txt', 'w+') command will leave an empty file, and the open('file.txt', 'r+') and open('file.txt', 'a+') will leave the files unchanged.

The difference between the "r +" and "a +" parameters is the behavior that others have suggested. The "r +" parameter allows you to write anywhere in the file, and "a +" forces everything to be written to the end of the file, regardless of where you set the current position of the file.

If you want to learn more about it, according to the python documentation , the open function accepts modes similar to the fopen function in C stdio.

+15
source

Not really. Using the append command, any records are written to the end of the file, where you can look for another place with the record.

+2
source

"W" will delete the content data and then search for the end position. So you will end up with an empty file with a pointer to BOF, not EOF. Use "A" to store old data.

+2
source

It depends on the system you are working on; opening a file with the add flag often means that you are going to write at the end of the file regardless of the position of the record pointer. In other words, this may mean that your OS must search to the end of the file before each entry, or simply search for the pointer to the end after opening. You can easily check how it works in your environment, but only guaranteed behavior seeks completion after opening.

EDIT: as other people have noted, the w flag effectively truncates the file. If you want to open it for updating without deleting the current content, you will need to use the r+ flag (but then reading will be allowed that does not match true for a ).

+1
source

Source: https://habr.com/ru/post/893902/


All Articles