chcę:Jak otworzyć (odczytać-zapisać) lub utworzyć plik z dozwolonym obcięciem?
- otworzyć plik w trybie read-write, jeśli istnieje;
- utworzyć, jeśli nie istnieje;
- być w stanie skrócić go w dowolnym miejscu i czasie.
EDIT: ze skróconej rozumiem napisać aż pozycji i usunąć pozostałą część pliku, jeśli jest obecny
Wszystko to atomowo (z jednym open()
rozmowy lub symulowanie jeden open()
połączenia)
Żaden pojedynczy otwarty modalność wydaje się zastosowanie:
- r: oczywiście nie działa;
- r +: zawiedzie, jeśli plik nie istnieje;
- w: odtworzyć plik, jeśli istnieje;
- w +: odtworzyć plik, jeśli istnieje;
- a: nie można odczytać;
- a +: nie można obciąć.
Niektóre kombinacje, które wypróbowałem (rw, rw +, r + w, itp.) Również nie działają. Czy to możliwe?
Niektóre doc z Ruby (dotyczy pytona zbyt):
r
Read-only mode. The file pointer is placed at the beginning of the file.
This is the default mode.
r+
Read-write mode. The file pointer will be at the beginning of the file.
w
Write-only mode. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
w+
Read-write mode. Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for reading and writing.
a
Write-only mode. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist,
it creates a new file for writing.
a+
Read and write mode. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
Więc zasadniczo chcesz zastąpić plik i upewnij się, że poprzednia zawartość nie pozostaje poniżej punktu, w którym przestałeś pisać? –
Tak. 'file.truncate()' działa w tym celu i działa, gdy plik jest "r +", "w", "w +". Ale wszystkie mają wady wymienione powyżej. – ceztko