我有有分数的档案:
Foo 12
Bar 44我试着整理它,删除它,而不是写排序的分数在里面。但我错了:
ValueError:关闭文件上的I/O操作
这是我的功能:
def Sort():
scores = []
with open("results.txt") as x:
for linia in x:
name,score=linia.split(' ')
score=int(score)
scores.append((name,score))
scores.sort(key=lambda sc: sc[1])
x.truncate()
for name, score in scores:
x.write(name+' '+str(score))发布于 2016-02-03 20:07:49
该文件仅在块的中保持打开。之后,Python将自动关闭它。您需要第二次打开它,使用第二个with块。
def Sort():
scores = []
with open("results.txt") as x:
# x is open only inside this block!
for linia in x:
name, score=linia.split(' ')
score = int(score)
scores.append((name, score))
scores.sort(key=lambda sc: sc[1])
with open("results.txt", "w") as x:
# open it a second time, this time with `w`
for name, score in scores:
x.write(name + ' ' + str(score))
Sort()这也可以通过只打开一个文件来完成。在本例中,您以双重读/写模式(r+)打开文件,并使用truncate删除以前的文件内容。
def Sort():
scores = []
with open("results.txt", "r+") as x:
for linia in x:
name, score = linia.split(' ')
score = int(score)
scores.append((name, score))
scores.sort(key=lambda sc: sc[1])
# Go to beginning of file
x.seek(0)
# http://devdocs.io/python~3.5/library/io#io.IOBase.truncate
# If no position is specified to truncate,
# then it resizes to current position
x.truncate()
# note that x.truncate(0) does **not** work,
# without an accompanying call to `seek`.
# a number of control characters are inserted
# for reasons unknown to me.
for name, score in scores:
x.write(name + ' ' + str(score) + '\n')然而,就我个人而言,我觉得第一种方法更好,而且你不太可能射中自己的脚。
https://stackoverflow.com/questions/35186450
复制相似问题