好的,我们走了,我一整天都在看这个,我疯了,我以为我做得很辛苦,但现在我卡住了。我正在制作游戏的高分榜,我已经创建了一个二进制文件,按顺序存储分数和名称。现在我必须做同样的事情,但将分数和名称存储在文本文件中。
这是二进制文件部分,但我不知道从哪里开始使用文本文件。
def newbinfile():
if not os.path.exists('tops.dat'):
hs_data = []
make_file = open('tops.dat', 'wb')
pickle.dump(hs_data, make_file)
make_file.close
else:
None
def highscore(score, name):
entry = (score, name)
hs_data = open('tops.dat', 'rb')
highsc = pickle.load(hs_data)
hs_data.close()
hs_data = open('tops.dat', 'wb+')
highsc.append(entry)
highsc.sort(reverse=True)
highsc = highsc[:5]
pickle.dump(highsc, hs_data)
hs_data.close()
return highsc
任何有关从何处开始的帮助将不胜感激。感谢
答案 0 :(得分:3)
我认为您应该使用with
个关键字。
您会找到与您要执行的操作相对应的示例here。
with open('output.txt', 'w') as f:
for l in ['Hi','there','!']:
f.write(l + '\n')
答案 1 :(得分:2)
从这里开始:
>>> mydata = ['Hello World!', 'Hello World 2!']
>>> myfile = open('testit.txt', 'w')
>>> for line in mydata:
... myfile.write(line + '\n')
...
>>> myfile.close() # Do not forget to close
编辑:
一旦熟悉了这一点,请使用with
关键字,当文件处理程序超出范围时,该关键字保证关闭:
>>> with open('testit.txt', 'w') as myfile:
... for line in mydata:
... myfile.write(line + '\n')
...
答案 2 :(得分:1)
Python具有内置方法,用于写入可用于写入文本文件的文件。
writer = open("filename.txt", 'w+')
# w+ is the flag for overwriting if the file already exists
# a+ is the flag for appending if it already exists
t = (val1, val2) #a tuple of values you want to save
for elem in t:
writer.write(str(elem) + ', ')
writer.write('\n') #the write function doesn't automatically put a new line at the end
writer.close()