我有分数文件:
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))
答案 0 :(得分:2)
该文件仅在内部 with
块中保持打开状态。之后,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')
然而,就个人而言,我觉得第一种方法更好,而且你不太可能用脚射击自己。