如果不存在,则写入新文件,如果存在,则附加到文件

我有一个程序,写一个用户的 highscore到一个文本文件。当用户选择 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.

以下是相关的代码,目前为止还不起作用:

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.

165539 次浏览

我不清楚您感兴趣的高分数到底存储在哪里,但是下面的代码应该是您需要检查文件是否存在并在需要时附加到它的代码。我更喜欢这种方法而不是“ try/竹篮打水一场空”。

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()

Have you tried mode 'a+'?

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

但是请注意,在 Python 2.x 中,f.tell()将返回0。

只要打开 'a'模式:

打开书写。如果文件不存在,则创建该文件。流定位在文件的末尾。

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

若要查看是否正在写入新文件,请检查流位置。如果为零,则该文件为空,或者是一个新文件。

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')

如果您仍在使用 Python2,那么为了绕过 窃听器,可以在 open之后添加 f.seek(0, os.SEEK_END),或者使用 io.open

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:

下面是处理这种情况的另一种解决办法:
(*)我使用 sys.stdoutprint而不是 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+'

使用 pathlib模块(python 的 面向对象的文件系统路径)

只是为了好玩,这可能是最新的 Python 版本的解决方案。

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}')