首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python文件读写

Python文件读写
EN

Stack Overflow用户
提问于 2016-02-03 19:56:02
回答 1查看 114关注 0票数 0

我有有分数的档案:

代码语言:javascript
复制
Foo 12
Bar 44

我试着整理它,删除它,而不是写排序的分数在里面。但我错了:

ValueError:关闭文件上的I/O操作

这是我的功能:

代码语言:javascript
复制
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))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-03 20:07:49

该文件仅在块的中保持打开。之后,Python将自动关闭它。您需要第二次打开它,使用第二个with块。

代码语言:javascript
复制
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删除以前的文件内容。

代码语言:javascript
复制
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')

然而,就我个人而言,我觉得第一种方法更好,而且你不太可能射中自己的脚。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35186450

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档