简体   繁体   English

Python文件读写

[英]Python file read and write

I have file with scores: 我有分数文件:

Foo 12
Bar 44

I try to sort it, erase it and than write sorted scores into it. 我尝试对其进行排序,擦除,然后将排序后的分数写入其中。 But I get error: 但是我得到了错误:

ValueError: I/O operation on closed file ValueError:对关闭的文件进行I / O操作

Here is my function: 这是我的功能:

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))

The file remains open only inside the with block. 该文件仅 with保持打开状态。 After that, Python will automatically close it. 之后,Python将自动关闭它。 You need to open it a second time, using a second with block. 您需要再次打开它,使用第二个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()

This can also be done using just a single file open. 也可以只打开一个文件即可完成此操作。 In this case, you open the file in a dual read/write mode (r+) and use truncate to erase the previous file contents. 在这种情况下,您可以在双读/写模式(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')

However, personally, I feel that the first approach is better, and you're less likely to shoot yourself in the foot. 但是,就我个人而言,我认为第一种方法更好,而且您不太可能用脚射击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM