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

编程入门 行业动态 更新时间:2024-10-07 01:30:28
本文介绍了如果新文件不存在,则写入新文件,如果存在则附加到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个将用户的 highscore 写入文本文件的程序。当用户选择 playername 时,该文件由用户命名。如果具有该特定用户名的文件已经存在,那么程序应该追加到文件中(这样你可以看到多个 highscore / code>)。如果使用该用户名的文件不存在(例如,如果用户是新的),它应该创建一个新的文件并写入。

这是相关的,迄今为止不工作,代码:

尝试:与打开(播放器):#播放器是变量将用户名输入以open(player,'a')存储为高分: highscore.write(用户名:,播放器) 除IOError外:打开(player +.txt,'w')为高分: highscore.write(用户名:,玩家)

上面的代码创建一个新的文件,如果它不存在,并写入它。如果它存在,我检查文件时没有任何附加信息,并且没有任何错误。 解决方案

我不清楚确切地说,你感兴趣的高分被存储在哪里,但是下面的代码应该是你需要检查文件是否存在并且如果需要附加到它的。

import os player ='bob' filename = player +'.txt' $ b如果os.path.exists(filename): append_write ='a'#如果已经存在,则追加 else: append_write ='w'#如果不是 则创建一个新文件highscore = open(filename,append_write) highscore.write(Username:+ player +'\ n') highscore.close()

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.

解决方案

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

更多推荐

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

本文发布于:2023-11-02 07:00:05,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:新文件   不存在   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!