티스토리 뷰

반응형

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

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

 

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

Read and overwrite a file in Python

파이썬에서 파일 읽기 및 덮어쓰기

 문제 내용 

Currently I'm using this:

현재 이 코드를 사용 중입니다:
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()

 

But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it.

하지만 문제는 이전 파일이 새 파일보다 크다는 것입니다. 그래서 새 파일 끝에 이전 파일의 일부가 포함된 새 파일이 만들어집니다.

 

 

 

 높은 점수를 받은 Solution 

If you don't want to close and reopen the file, to avoid race conditions, you could truncate it:

경쟁 조건을 피하기 위해 파일을 닫고 다시 열지 않으려면, 다음과 같이 파일을 잘라내면 됩니다:
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()

 

The functionality will likely also be cleaner and safer using open as a context manager, which will close the file handler, even if an error occurs!

기능을 보다 깨끗하고 안전하게 사용하려면, 파일 핸들러를 닫아줄 컨텍스트 매니저로 open을 사용하는 것이 좋습니다. 이렇게 하면 오류가 발생하더라도 파일 핸들러가 닫힙니다!
with open(filename, 'r+') as f:
    text = f.read()
    text = re.sub('foobar', 'bar', text)
    f.seek(0)
    f.write(text)
    f.truncate()

 

 

 가장 최근 달린 Solution 

I find it easier to remember to just read it and then write it.

제 경우에는 그냥 읽은 후에 쓰기만 하는 게 더 쉬운 것 같습니다.

 

For example:

예를 들어:
with open('file') as f:
    data = f.read()
with open('file', 'w') as f:
    f.write('hello')

 

 

출처 : https://stackoverflow.com/questions/2424000/read-and-overwrite-a-file-in-python

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