附加到txt文件中的现有行 [英] appending to an existing line in a txt file

查看:128
本文介绍了附加到txt文件中的现有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如这是我目前的代码:

我有一个程序来存储一个人的名字和他们的分数,
$ b $

  name = input(Name:)
score = input(Score:)

file_name =student_scores.txt

file = open(file_name,'a')
file.write(str(name)+,+ str(score)+\ n)
file.close()

输出txt文件是(name = bob)和(score = 1):

$ p $ bob,1

$ b pre> bob,1
bob,2

然而,我怎样才能改变我的代码,以便txt文件如下所示:

  bob,1,2 


解决方案

将现有文件的数据存储在名为key的字典中,成绩列表作为价值。这段代码将把现有的数据存储到一个字典中,给它添加新的分数,并将字典写入格式正确的文件。

 从集合中导入os 
import defaultdict

$ b def scores_to_dict(file_name):
返回名称/分数列表的defaultdict作为键/值
如果不是os.path.isfile(file_name):
返回defaultdict(list)
打开(file_name,'r')作为f:
content = f.readlines ()
content = [line.strip('\\\
')。split(',')for line in content]
temp_dict = {line [0]:line [1:] for line在内容中}
d = defaultdict(list)
d.update(temp_dict)
return d


name = input(Name:)
分数=输入(分数:)

d = scores_to_dict('student_scores.txt')
d [name] .append(分数)

打开('student_scores.txt','w')为f:
for k,v in d.items():
f.write(','.jo in([k] + v)+'\\\
')


I have a program to store a persons name and their score, in a txt file in python.

for example this is my current code :

name = input("Name: ")
score = input("Score: ")

file_name = "student_scores.txt" 

file = open(file_name , 'a') 
file.write(str(name)  + ", " + str(score) + "\n") 
file.close() 

The output txt file is, (name = bob) and (score = 1) :

bob, 1

When i enter another score (2) for the same person (bob) the txt file looks like this:

bob, 1
bob, 2

However how can i change my code, so that the txt file looks like this :

bob, 1, 2

解决方案

Store the data of the existing file in a dictionary with name as key and list of scores as value. This code will store the existing data to a dictionary, add new score to it and write the dictionary to file with proper formatting.

import os
from collections import defaultdict


def scores_to_dict(file_name):
    """Returns a defaultdict of name / list of scores as key / value"""
    if not os.path.isfile(file_name):
        return defaultdict(list)
    with open(file_name, 'r') as f:
        content = f.readlines()
    content = [line.strip('\n').split(', ') for line in content]
    temp_dict = {line[0]: line[1:] for line in content}
    d = defaultdict(list)
    d.update(temp_dict)
    return d


name = input("Name: ")
score = input("Score: ")

d = scores_to_dict('student_scores.txt')
d[name].append(score)

with open('student_scores.txt', 'w') as f:
    for k, v in d.items():
        f.write(', '.join([k] + v) + '\n')

这篇关于附加到txt文件中的现有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆