복붙노트

[PYTHON] 절단 (truncation)이 가능한 파일을 열거 나 (읽기 / 쓰기) 작성하는 방법은 무엇입니까?

PYTHON

절단 (truncation)이 가능한 파일을 열거 나 (읽기 / 쓰기) 작성하는 방법은 무엇입니까?

나는 다음과 같이하고 싶다.

편집 : 잘라내 기와 함께 나는 위치까지 쓰고 파일의 나머지 부분을 버리는 것을 의미한다.

이 모든 것은 원자 적으로 (단일 open () 호출 또는 단일 open () 호출을 시뮬레이트 함으로)

단일 열린 양식이 적용되는 것 같지 않습니다.

내가 시도한 일부 조합 (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.

해결법

  1. ==============================

    1.OpenGroup에 따르면 :

    OpenGroup에 따르면 :

    따라서 "w"또는 "w +"가있는 파일을 열 때 O_TRUNC가 아마도 전달됩니다. 이것은 "절단"을 다른 의미로, 내가 원하는 것을 제공하지 않습니다.

    파이썬에서는 os.open () 함수로 저수준 I / O에서 파일을 여는 것처럼 보입니다.

    다음과 같은 파이썬 함수 :

    def touchopen(filename, *args, **kwargs):
        # Open the file in R/W and create if it doesn't exist. *Don't* pass O_TRUNC
        fd = os.open(filename, os.O_RDWR | os.O_CREAT)
    
        # Encapsulate the low-level file descriptor in a python file object
        return os.fdopen(fd, *args, **kwargs)
    

    내가 원하는 행동을했다. 당신은 이것을 다음과 같이 사용할 수있다. (실제로는 나의 유스 케이스이다.)

    # Open an existing file or create if it doesn't exist
    with touchopen("./tool.run", "r+") as doing_fd:
    
        # Acquire a non-blocking exclusive lock
        fcntl.lockf(doing_fd, fcntl.LOCK_EX)
    
        # Read a previous value if present
        previous_value = doing_fd.read()
        print previous_value 
    
        # Write the new value and truncate
        doing_fd.seek(0)
        doing_fd.write("new value")
        doing_fd.truncate()
    
  2. ==============================

    2.글쎄,이 모드들만 있고, 모두 당신이 열거 한 "결함들"이 있습니다.

    글쎄,이 모드들만 있고, 모두 당신이 열거 한 "결함들"이 있습니다.

    유일한 옵션은 open ()을 래핑하는 것입니다. 왜 이런 식으로하지? (파이썬)

    def touchopen(filename, *args, **kwargs):
        open(filename, "a").close() # "touch" file
        return open(filename, *args, **kwargs)
    

    그것은 마치 열려있는 것처럼 행동하고, 정말로 원한다면 다시 열 수 있습니다.

    모든 오픈 기능이 보존되므로 다음과 같이 할 수 있습니다.

    with touchopen("testfile", "r+") as testfile:
        do_stuff()
    

    물론, + 모드로 파일을 열고, 메모리로 읽어 들이고, w 모드로 임시 파일을 마술로 만들어 잘라내기를 처리하는 문맥 관리자를 만들 수 있으며, 닫을 때 임시 파일의 이름을 원래 파일로 바꿀 수 있습니다. 그러나 그것은 내가 추측하는 과잉 일 것이다.

  3. ==============================

    3."a +"(Ruby)로 읽고 쓰고자를 수 있습니다.

    "a +"(Ruby)로 읽고 쓰고자를 수 있습니다.

    File.open("test.txt", "a+") do |f|
      f.print "abc\ndefgh" 
      f.rewind
      p f.read 
      f.truncate(5) 
    end
    puts File.size("test.txt") #=> 5
    
  4. ==============================

    4.나는 루비에서 이것을 정확히 수행하는 우아한 방법을 모른다. 내 솔루션 아마도 임시 파일을 만들고, 내용을 쓰고, 그리고 내가 정말로 원했던 파일 이름으로 이름을 바꿀 것입니다. 이전 파일이 있으면 덮어 쓰거나 그렇지 않으면 파일을 만듭니다. 이 같은:

    나는 루비에서 이것을 정확히 수행하는 우아한 방법을 모른다. 내 솔루션 아마도 임시 파일을 만들고, 내용을 쓰고, 그리고 내가 정말로 원했던 파일 이름으로 이름을 바꿀 것입니다. 이전 파일이 있으면 덮어 쓰거나 그렇지 않으면 파일을 만듭니다. 이 같은:

    orig_filename = './whatever_file.log'
    temp_filename = './.tempfile'
    temp_file = File.new(temp_filename, 'w')
    
    // Write contents to file
    
    temp_file.close
    File.rename(temp_filename, orig_filename)
    

    어떤 이유로 든 실패하면 이름을 바꾸면 SystemCallError가 발생합니다.

  5. from https://stackoverflow.com/questions/10349781/how-to-open-read-write-or-create-a-file-with-truncation-allowed by cc-by-sa and MIT license