如何正确地将元组列表写入.txt文件?

时间:2015-11-25 21:55:12

标签: python list file sorted

我正在尝试按名称和时间维护列表,按时间增加排序。

def listfile (name, time):

    players = []
    strtime = str(time)
    players.append((name, strtime))
    with open("playersScores.txt", "r") as f:
        for line in f:
            if line != '\n':
                name, strtime = line.split(',')
                players.append((name, strtime))
    f.close()  

    players.sort(key=lambda tup: tup[1])

    with open("playersScores.txt", "w") as f:
        for (name, strtime) in players:
            f.write("%s\n" % (name + "," + strtime))
    f.close() 

这基本上有效但除了新添加的行之外,它在每行下面留下一个空行。

我想要像:

Bob,32.82
Bill,34.22
Joe,39.09
Bob,45.23
George,46.08

但我得到了:

Bob,32.82

Bill,34.22
Joe,39.09

Bob,45.23

George,46.08

Bill,34.22是最后一个条目。

2 个答案:

答案 0 :(得分:5)

问题在于,在阅读文件时,每行末尾都有一个\n,不会自动被剥离。在此处显示的代码中,变量strtime最后仍包含\n个字符。

name, strtime = line.split(',')
players.append((name, strtime))

\n来电中的f.write()没问题。您只需要在阅读时剥离\nrstrip()将从字符串的右侧删除空格字符。

这样做:

name, strtime = line.split(',')
players.append((name, strtime.rstrip()))

答案 1 :(得分:1)

由于您创建的是技术上的.csv文件,您还可以查看csv模块

import csv
import itertools

with open('path/to/file.txt', 'r+') as f:
    reader = csv.reader(f)
    new_lines = sorted(itertools.chain(reader, (name, strtime)),
                       key=lambda x: float(x[1]))
    f.seek(0)  # rewind to the beginning of the file
    writer = csv.writer(f, lineterminator="\n")
    # you must specify the lineterminator on Windows, or else open in binary mode
    # however csv.readers don't work in binary mode on Windows.
    writer.writerows(new_lines)

请注意,如果您删除行,这会给您一些奇怪的错误。这不会在写入文件之前截断文件 - 您要覆盖数据,因此替换

1
3
5
7

2
4
8

会给你

2
4
8
7  # oops!