Python 如果新文件不存在则写入新文件,如果存在则追加到文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20432912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:26:06  来源:igfitidea点击:

Writing to a new file if it doesn't exist, and appending to a file if it does

pythonpython-3.xfileappend

提问by Bondenn

I have a program which writes a user's highscoreto a text file. The file is named by the user when they choose a playername.

我有一个将用户写入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.

如果具有该特定用户名的文件已存在,则程序应附加到该文件(以便您可以看到多个highscore)。如果具有该用户名的文件不存在(例如,如果用户是新用户),则应创建一个新文件并写入该文件。

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.

如果文件不存在,上面的代码会创建一个新文件,并写入它。如果它存在,当我检查文件时没有附加任何内容,并且我没有收到任何错误。

采纳答案by qmorgan

It's not clear to me exactly where the high-score that you're interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the "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()

回答by Eric des Courtis

Have you tried mode 'a+'?

你试过模式'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/issue22651for details.

但是请注意,这f.tell()将在 Python 2.x 中返回 0。有关详细信息,请参阅https://bugs.python.org/issue22651

回答by user

Just open it in 'a'mode:

只需在'a'模式下打开它:

a  Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.

a  开放写作。如果文件不存在,则创建该文件。流位于文件的末尾。

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

To see whether you're writing to a new file, check the stream position. If it's zero, either the file was empty or it is a new file.

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

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

If you're still using Python 2, to work around the bug, either add f.seek(0, os.SEEK_END)right after openor use io.openinstead.

如果你还在使用Python 2,要解决的bug,要么添加f.seek(0, os.SEEK_END)之后open或使用io.open替代。