将字典数据写入文件

时间:2015-11-27 19:57:10

标签: python-3.x

我有一本字典,当保存到文件时输出:

m_xSize * m_ySize

我希望输出格式为

Score,5
Name, Lenard

我该怎么做?我怎样才能读取写入文件的数据并对其进行排序。

1 个答案:

答案 0 :(得分:1)

你可以做这样的事情,虽然看到你已经尝试过的东西会很高兴:

在python文件中定义一些数据

scores = [
        {'name': 'Lenard', 'score': 5 },
        {'name': 'Tim', 'score': 10}
        ]

file = 'students.txt'

编写一个函数来填充带有数据的文件

def writefile():
    fil = open(file, 'w')       # open file
    fil.truncate()              # truncate the contents of the file
    fil.write("Name\tScore")    # write heading
    for score in scores:        # write each record
        fil.write("\n%s\t%s" % (score['name'], score['score']))
    fil.close()                 # close file

编写一个函数来读取文件

def readfile():
    with open(file) as fil:     # open file
        scores = fil.read().splitlines() # split file contents by lines

    count = 0
    for score in scores:        # loop through all lines
        if count == 0:          # skip first line
            count = count + 1
            continue
        data = score.split()    # split line by space
        print ("%s\t%s" % (data[0], data[1])) # print name and score

调用您的函数

writefile() # write file with scores
print ('file written\n----')
print ('read file and print contents below')
readfile()  # read file with score

结果:

$ /c/Python34/python.exe test.py
file written
----
read file and print contents below
Lenard  5
Tim     10

您的文件将如下所示(数据由标签分隔):

  Name    Score
  Lenard  5
  Tim 10

您可以使用上面使用的一些关键字,找到更好的创建程序的方法。请注意,scores变量是一个dicts列表。