Как открыть (прочитать -записать )или создать файл с разрешенным усечением?

Я хочу:

  • открыть файл в режиме чтения -записи, если он существует;
  • создать его, если он не существует;
  • иметь возможность обрезать его в любое время -в любом месте.

РЕДАКТИРОВАТЬ:с усечением Я имею в виду запись до позиции и отбрасывание оставшейся части файла, если она присутствует

Все это атомарно (с одним вызовом open()или имитацией одного вызова open())

Похоже, что ни одна открытая модальность не применима:

  • r :явно не работает;
  • r+ :ошибка, если файл не существует;
  • w :воссоздать файл, если он существует;
  • w+ :воссоздать файл, если он существует;
  • a :не умеет читать;
  • a+ :не может усекаться.

Некоторые комбинации, которые я пробовал, (rw, rw+, r+w и т. д. )похоже, тоже не работают. Является ли это возможным?

Некоторые документы из Ruby (применимы и к python):

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.

36
задан ceztko 7 July 2017 в 10:32
поделиться