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

Writing to a new file if it doesn#39;t exist, and appending to a file if it does(如果新文件不存在则写入新文件,如果存在则追加到文件)
本文介绍了如果新文件不存在则写入新文件,如果存在则追加到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序将用户的 highscore 写入文本文件.该文件由用户在选择 playername 时命名.

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.

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

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.

推荐答案

我不清楚你感兴趣的高分到底存储在哪里,但是下面的代码应该是你需要检查的文件存在并在需要时附加到它.我更喜欢这种方法而不是try/except".

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 + '
')
highscore.close()

这篇关于如果新文件不存在则写入新文件,如果存在则追加到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)