티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Writing to a new file if it doesn't exist, and appending to a file if it does
파일이 없으면 새 파일에 쓰고, 있으면 추가로 쓰기
문제 내용
I have a program which writes a user's highscore
to a text file. The file is named by the user when they choose a playername
.
유저의 하이스코어를 텍스트 파일에 쓰는 프로그램이 있습니다. 파일 이름은 사용자가 플레이어 이름을 선택할 때 지정됩니다.
If the file with that specific username already exists, then the program should append to the file (so that you can see more than one highscore
). And if a file with that username doesn't exist (for example, if the user is new), it should create a new file and write to it.
해당 사용자명의 파일이 이미 존재하는 경우 프로그램은 파일에 추가해야 합니다(그렇게 하면 하이스코어가 하나 이상 표시됩니다). 그리고 사용자명에 해당하는 파일이 없는 경우(예: 사용자가 새로운 경우) 새 파일을 만들어 써야 합니다.
Here's the relevant, so far not working, code:
다음은 작동하지 않는 코드입니다.
try:
with open(player): #player is the varible storing the username input
with open(player, 'a') as highscore:
highscore.write("Username:", player)
except IOError:
with open(player + ".txt", 'w') as highscore:
highscore.write("Username:", player)
The above code creates a new file if it doesn't exist, and writes to it. If it exists, nothing has been appended when I check the file, and I get no errors.
위 코드는 파일이 존재하지 않으면 새 파일을 생성하고 쓰는데 문제가 없지만, 파일이 이미 존재하는 경우 추가되지 않고 오류도 발생하지 않습니다.
높은 점수를 받은 Solution
Have you tried mode 'a+'?
'mode'를 'a+'로 변경해 보세요.
with open(filename, 'a+') as f:
f.write(...)
Note however that f.tell()
will return 0 in Python 2.x. See https://bugs.python.org/issue22651 for details.
그러나 Python 2.x에서는 f.tell()이 0을 반환합니다. 자세한 내용은 https://bugs.python.org/issue22651을 참조하세요.
가장 최근 달린 Solution
Notice that if the file's parent folder doesn't exist you'll get the same error:
부모 폴더가 존재하지 않으면 동일한 오류가 발생한다는 점에 유의하세요:
IOError: [Errno 2] No such file or directory:
Below is another solution which handles this case:
(*) I used sys.stdout
and print
instead of f.write
just to show another use case
아래는 이 경우를 처리하는 또 다른 솔루션입니다: (*) f.write 대신 sys.stdout과 print를 사용하여 다른 사용 사례를 보여주기 위해 사용하였습니다.
# Make sure the file's folder exist - Create folder if doesn't exist
folder_path = 'path/to/'+folder_name+'/'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
print_to_log_file(folder_path, "Some File" ,"Some Content")
Where the internal print_to_log_file
just take care of the file level:
내부 print_to_log_file이 파일 레벨을 처리합니다::
# If you're not familiar with sys.stdout - just ignore it below (just a use case example)
def print_to_log_file(folder_path ,file_name ,content_to_write):
#1) Save a reference to the original standard output
original_stdout = sys.stdout
#2) Choose the mode
write_append_mode = 'a' #Append mode
file_path = folder_path + file_name
if (if not os.path.exists(file_path) ):
write_append_mode = 'w' # Write mode
#3) Perform action on file
with open(file_path, write_append_mode) as f:
sys.stdout = f # Change the standard output to the file we created.
print(file_path, content_to_write)
sys.stdout = original_stdout # Reset the standard output to its original value
Consider the following states:
다음과 같은 상태를 고려해보세요:
'w' --> Write to existing file
'w+' --> Write to file, Create it if doesn't exist
'a' --> Append to file
'a+' --> Append to file, Create it if doesn't exist
In your case I would use a different approach and just use 'a'
and 'a+'
.
당신의 경우, 'a'와 'a+'를 사용하는 다른 접근법을 사용하는 것이 좋을 것입니다.
출처 : https://stackoverflow.com/questions/20432912/writing-to-a-new-file-if-it-doesnt-exist-and-appending-to-a-file-if-it-does
'개발 > 파이썬' 카테고리의 다른 글
Python에서 변수가 dictionary인지 확인하는 방법 (0) | 2023.02.14 |
---|---|
Pandas DataFrame를 딕셔너리로 변환하기 (0) | 2023.02.14 |
두 값 사이에 있는 숫자로 이루어진 리스트 만들기 (0) | 2023.02.13 |
파이썬 딕셔너리를 문자열로 변환하고 다시 되돌리는 방법 (0) | 2023.02.13 |
파이썬에서 딕셔너리를 반복하면서 항목을 삭제하기 (0) | 2023.02.12 |