[英]Python file read and write
我有分数文件:
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))
该文件仅在 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')
但是,就我个人而言,我认为第一种方法更好,而且您不太可能用脚射击。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.