티스토리 뷰

개발/파이썬

기존 파일에 내용 추가하기

맨날치킨 2022. 12. 3. 09:05
반응형

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

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

 

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

How do I append to a file?

기존 파일에 내용 추가하기

 문제 내용 

How do I append to a file instead of overwriting it?

파일을 덮어쓰지 않고 파일에 내용을 추가하려면 어떻게 해야 합니까?

 

 

 

 높은 점수를 받은 Solution 

Set the mode in open() to "a" (append) instead of "w" (write):

모드를 "w"(쓰기) 대신 "a"(첨부)로 설정합니다.
with open("test.txt", "a") as myfile:
    myfile.write("appended text")

 

The documentation lists all the available modes.

설명서에는 사용 가능한 모든 모드가 나열되어 있습니다.

 

 

 

 가장 최근 달린 Solution 

If multiple processes are writing to the file, you must use append mode or the data will be scrambled. Append mode will make the operating system put every write, at the end of the file irrespective of where the writer thinks his position in the file is. This is a common issue for multi-process services like nginx or apache where multiple instances of the same process, are writing to the same log file. Consider what happens if you try to seek, then write:

여러 프로세스가 파일에 쓰는 경우 추가 모드를 사용해야 합니다. 그렇지 않으면 데이터가 스크램블됩니다. 추가 모드는 작성자가 파일에서 자신의 위치가 어디라고 생각하는지에 관계없이 운영 체제가 파일 끝에 모든 쓰기를 넣도록 합니다. 이는 동일한 프로세스의 여러 인스턴스가 동일한 로그에 기록되는 nginx 또는 apache와 같은 다중 프로세스 서비스에서 일반적인 문제입니다. 네가 검색하려고 하면 어떻게 되는지 생각해 보고 다음과 같이 적습니다.
Example does not work well with multiple processes: 

f = open("logfile", "w"); f.seek(0, os.SEEK_END); f.write("data to write");

writer1: seek to end of file.           position 1000 (for example)
writer2: seek to end of file.           position 1000
writer2: write data at position 1000    end of file is now 1000 + length of data.
writer1: write data at position 1000    writer1's data overwrites writer2's data.

 

By using append mode, the operating system will place any write at the end of the file.

append 모드를 사용하면 운영 체제가 파일 끝에 쓰기를 배치합니다.
f = open("logfile", "a"); f.seek(0, os.SEEK_END); f.write("data to write");

 

Append most does not mean, "open file, go to end of the file once after opening it". It means, "open file, every write I do will be at the end of the file".

대부분 추가는 "파일을 연 후 파일의 끝으로 한 번 이동"을 의미하지 않습니다. 그것은 "파일 열기, 내가 하는 모든 쓰기가 파일의 끝에 있을 것"을 의미한다.

 

WARNING: For this to work you must write all your record in one shot, in one write call. If you split the data between multiple writes, other writers can and will get their writes in between yours and mangle your data.

경고: 이 기능을 사용하려면 모든 기록을 한 번에, 한 번의 쓰기 호출로 작성해야 합니다. 여러 개의 쓰기로 데이터를 분할하면 다른 작성자가 사용자의 쓰기 작업을 수행하여 데이터를 망칠 수 있습니다.

 

 

 

출처 : https://stackoverflow.com/questions/4706499/how-do-i-append-to-a-file

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