Bon*_*enn 47 python file append python-3.x
我有一个程序将用户写入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)
Run Code Online (Sandbox Code Playgroud)
上面的代码创建一个新文件(如果它不存在)并写入它.如果它存在,检查文件时没有附加任何内容,我没有错误.
Eri*_*tis 57
你尝试过'a +'模式吗?
with open(filename, 'a+') as f:
f.write(...)
Run Code Online (Sandbox Code Playgroud)
但请注意,f.tell()它将在Python 2.x中返回0.有关详细信息,请参阅https://bugs.python.org/issue22651.
qmo*_*gan 33
我不清楚你感兴趣的高分存储的确切位置,但下面的代码应该是你需要检查文件是否存在并在需要时附加到它的位置.我更喜欢这种方法的"尝试/除外".
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()
Run Code Online (Sandbox Code Playgroud)
use*_*ser 10
只需在'a'模式下打开它:
a开放写作.如果文件不存在,则创建该文件.流位于文件的末尾.
with open(filename, 'a') as f:
f.write(...)
Run Code Online (Sandbox Code Playgroud)
要查看您是否正在写入新文件,请检查流位置.如果它为零,则文件为空或者是新文件.
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')
Run Code Online (Sandbox Code Playgroud)
如果你还在使用Python 2,要解决的bug,要么添加f.seek(0, os.SEEK_END)之后open或使用io.open替代.
| 归档时间: |
|
| 查看次数: |
61169 次 |
| 最近记录: |