programing

새 파일이 없는 경우 파일에 쓰고 파일이 있는 경우 파일에 추가

stoneblock 2023. 5. 24. 21:38

새 파일이 없는 경우 파일에 쓰고 파일이 있는 경우 파일에 추가

사용자 정보를 작성하는 프로그램이 있습니다.highscore텍스트 파일에 저장합니다.파일 이름은 사용자가 선택할 때 지정합니다.playername.

해당 사용자 이름을 가진 파일이 이미 존재하는 경우 프로그램이 파일에 추가되어야 합니다(둘 이상을 볼 수 있음).highscore또한 해당 사용자 이름을 가진 파일이 존재하지 않는 경우(예: 사용자가 새로 온 경우) 새 파일을 생성하고 파일에 써야 합니다.

다음은 현재까지 작동하지 않는 관련 코드입니다.

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)

위의 코드는 파일이 없는 경우 새 파일을 만들고 파일에 씁니다.파일이 있으면 파일을 확인할 때 아무 것도 추가되지 않고 오류가 발생하지 않습니다.

모드 'a+'를 사용해 보셨습니까?

with open(filename, 'a+') as f:
    f.write(...)

그러나 참고:f.tell()Python 2.x에서 0을 반환합니다.자세한 내용은 https://bugs.python.org/issue22651 을 참조하십시오.

관심 있는 높은 점수가 정확히 어디에 저장되어 있는지는 모르겠지만, 아래 코드는 파일이 있는지 확인하고 필요한 경우 추가해야 하는 코드여야 합니다."try/except"보다 이 방법이 더 좋습니다.

import os
player = 'bob'

filename = player+'.txt'

if os.path.exists(filename):
    append_write = 'a' # append if already exists
else:
    append_write = 'w' # make a new file if not

highscore = open(filename,append_write)
highscore.write("Username: " + player + '\n')
highscore.close()

모드에서 열기만 하면 됩니다.

a쓰기를 위해 열려 있습니다.파일이 없는 경우 파일이 만들어집니다.스트림은 파일 끝에 위치합니다.

with open(filename, 'a') as f:
    f.write(...)

새 파일에 쓸지 여부를 확인하려면 스트림 위치를 확인합니다.0이면 파일이 비어 있거나 새 파일입니다.

with open('somefile.txt', 'a') as f:
    if f.tell() == 0:
        print('a new file or the file was empty')
        f.write('The header\n')
    else:
        print('file existed, appending')
    f.write('Some data\n')

만약 당신이 여전히 파이썬 2를 사용하고 있다면, 버그를 해결하기 위해, 추가하세요.f.seek(0, os.SEEK_END)바로 뒤에open또는 대신 사용합니다.

파일의 상위 폴더가 없는 경우 동일한 오류가 발생합니다.

IO 오류: [Errno 2] 해당 파일 또는 디렉터리가 없습니다.

다음은 이 경우를 처리하는 또 다른 솔루션입니다.
(*) 사용했습니다.sys.stdout그리고.print대신에f.write다른 사용 사례를 보여주기 위해

# 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")

내부의 위치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

다음 상태를 고려합니다.

'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

당신의 경우, 저는 다른 접근법을 사용하고 그냥 사용할 것입니다.'a'그리고.'a+'.

사용pathlibmodule(서버의 객체 지향 파일 시스템 경로)

재미삼아, 이것은 아마도 가장 최신의 파이썬 솔루션일 것입니다.

from pathlib import Path 

path = Path(f'{player}.txt')
path.touch()  # default exists_ok=True
with path.open('a') as highscore:
   highscore.write(f'Username:{player}')

언급URL : https://stackoverflow.com/questions/20432912/writing-to-a-new-file-if-it-doesnt-exist-and-appending-to-a-file-if-it-does