티스토리 뷰

반응형

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

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

 

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

How to modify a text file?

어떻게 텍스트 파일을 수정할 수 있나요?

 문제 내용 

I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?

저는 Python을 사용하고 있으며, 파일을 삭제하거나 복사하지 않고 텍스트 파일에 문자열을 삽입하려고 합니다. 어떻게 해야 할까요?

 

 

 

 높은 점수를 받은 Solution 

Unfortunately there is no way to insert into the middle of a file without re-writing it. As previous posters have indicated, you can append to a file or overwrite part of it using seek but if you want to add stuff at the beginning or the middle, you'll have to rewrite it.

불행히도 파일 중간에 삽입하는 방법은 다시 작성하지 않으면 불가능합니다. 이전 포스터들이 지적한 대로 파일에 추가하거나 일부분을 덮어쓸 수 있지만, 시작 부분이나 중간에 무언가를 추가하려면 다시 작성해야 합니다.

 

This is an operating system thing, not a Python thing. It is the same in all languages.

이것은 파이썬이나 언어와는 무관한 운영 체제의 문제입니다. 모든 언어에서 동일합니다.

 

What I usually do is read from the file, make the modifications and write it out to a new file called myfile.txt.tmp or something like that. This is better than reading the whole file into memory because the file may be too large for that. Once the temporary file is completed, I rename it the same as the original file.

보통 파일에서 읽어서 수정하고 myfile.txt.tmp와 같은 새 파일로 쓰는 것입니다. 전체 파일을 메모리에 읽는 것보다 이 방법이 더 나은 이유는 파일이 너무 커서 메모리에 다 담을 수 없을 수도 있기 때문입니다. 일단 임시 파일이 완성되면 원래 파일과 같은 이름으로 바꿔주는 것입니다.

 

This is a good, safe way to do it because if the file write crashes or aborts for any reason, you still have your untouched original file.

이 방법은 좋은, 안전한 방법입니다. 파일 쓰기가 충돌하거나 중단되는 경우에도 원래 파일을 그대로 가지고 있을 수 있습니다.

 

 

 

 가장 최근 달린 Solution 

As mentioned by Adam you have to take your system limitations into consideration before you can decide on approach whether you have enough memory to read it all into memory replace parts of it and re-write it.

Adam이 언급한 대로 시스템 제한 사항을 고려해야 하며, 메모리가 충분한지 여부에 따라 접근 방식을 결정할 수 있습니다.

 

If you're dealing with a small file or have no memory issues this might help:

작은 파일이거나 메모리 문제가 없는 경우 다음 방법이 도움이 될 수 있습니다.

 

Option 1) Read entire file into memory, do a regex substitution on the entire or part of the line and replace it with that line plus the extra line. You will need to make sure that the 'middle line' is unique in the file or if you have timestamps on each line this should be pretty reliable.

옵션 1) 파일 전체를 메모리에 읽어들인 다음 정규식 치환을 사용하여 전체 또는 일부분의 줄을 찾아 해당 줄에 추가 줄을 포함시킵니다. "중간 줄"이 파일에서 고유해야 하거나 각 줄에 타임스탬프가 있는 경우 신뢰성이 높을 것입니다.
# open file with r+b (allow write and binary mode)
f = open("file.log", 'r+b')   
# read entire content of file into memory
f_content = f.read()
# basically match middle line and replace it with itself and the extra line
f_content = re.sub(r'(middle line)', r'\1\nnew line', f_content)
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content 
f.truncate()
# re-write the content with the updated content
f.write(f_content)
# close file
f.close()

 

Option 2) Figure out middle line, and replace it with that line plus the extra line.

옵션 2) "중간 줄"을 찾아 해당 줄에 추가 줄을 포함시킵니다.
# open file with r+b (allow write and binary mode)
f = open("file.log" , 'r+b')   
# get array of lines
f_content = f.readlines()
# get middle line
middle_line = len(f_content)/2
# overwrite middle line
f_content[middle_line] += "\nnew line"
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content 
f.truncate()
# re-write the content with the updated content
f.write(''.join(f_content))
# close file
f.close()

 

 

출처 : https://stackoverflow.com/questions/125703/how-to-modify-a-text-file

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