티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to open a file for both reading and writing?

읽기 및 쓰기를 위해 파일을 열려면 어떻게 해야 할까요?

 문제 내용 

Is there a way to open a file for both reading and writing?

파일을 읽기 및 쓰기 위해 열 수 있는 방법이 있을까요?

 

As a workaround, I open the file for writing, close it, then open it again for reading. But is there a way to open a file for both reading and writing?

해결책으로 파일을 쓰기 위해 열고 닫은 다음, 다시 읽기 위해 열고 닫습니다. 하지만 파일을 읽기 및 쓰기 위해 열 수 있는 방법이 있을까요?

 

 

 

 높은 점수를 받은 Solution 

Here's how you read a file, and then write to it (overwriting any existing data), without closing and reopening:

다음은 파일을 읽은 후 (기존 데이터를 덮어쓰기) 쓰는 방법입니다. 이때 파일을 닫지 않고 바로 쓸 수 있습니다.
with open(filename, "r+") as f:
    data = f.read()
    f.seek(0)
    f.write(output)
    f.truncate()

 

 

 가장 최근 달린 Solution 

Summarize the I/O behaviors:

I/O 동작을 요약하면:

 

Mode r r+ w w+ a a+
Read + +   +   +
Write   + + + + +
Create     + + + +
Cover     + +    
Point in the beginning + + + +    
Point in the end         + +

 

Decision tree for the table above:

위 표에 대한 의사 결정 트리:

 

 

 

출처 : https://stackoverflow.com/questions/6648493/how-to-open-a-file-for-both-reading-and-writing

반응형
댓글
공지사항
최근에 올라온 글