Python:从文件中读取数据,并根据可以更改的给定模板将其打印到文件中

2024-09-28 17:31:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我对这个地方和python编程非常陌生,因此我必须编写一个python程序,如下所示:

1.student.txt文件中存在多个条目,用于不同的主题字段,如每个学生的Rollno、StudName、subject、Marks

e.g

<Rollno>,<StudName>,<Marks>,<Subject> #not required to be in file

101,Santosh , maths, 35

102, Hina, English, 41

101,Santosh , Hindi, 30

2.根据下面的模板文件(tempstrud.txt)为每个学生合并student.txt数据。每个学生的总数应显示在记录末尾的下方

Template:
{Id:<Rollno>, Name:<StudName>,subject:<Subject>,marks:<Marks>}

e.g

Santosh.101.txt

{Id: 101,name:Santosh , Subject: maths, Marks:35}

{Id: 101,name:Santosh , Subject: Hindi, Marks:30}

Total Marks :65
3.Create different files for each student , filename of this output file should be <Name>.<rollno>.txt

Note:
Supposing I am changing the template file as below 

{ marks:<Marks>-Id#<Rollno>-Name:<StudName>-subject#<Subject>}

I can also make changes to data files as below(changing column fields )

<Subject>,<RollNo>,<StudName>,<Marks>
maths,101,Santosh , 35
English,102, Hina, , 41
Hindi, 101,Santosh , 30

Code should  be generic enough for above changes also.

我编写了以下代码:

# variables used
List = []     # To hold the records of students
rolenum = []  # To hold all the rolenumbers
i = 0         #counter variable
#template
Template={}
# function to write into the file
def write(MyList, id=0):
    s = open(MyList[1] + "." + id + ".txt", 'a')
    s.writelines("Id: " + MyList[0] + " Name: " + MyList[1] + " Subject: " + MyList[2] + " Marks: " + MyList[3] + '\n')
    return (s, int(MyList[3])) # returns the file descriptor and the individual subject score

# Open the file to read the data into a List
with open('student.txt', 'r') as f:
    for line in f:
        tmp = line.strip().split(',')
        List.append(tmp)  # Contains all the student details

len = len(List)  # Total no. of Records

while i < len:
    if (List[i][0]) not in rolenum:
        rolenum.append(List[i][0])  # Finding all the Rolenumbers to use it as a key to individual student record
    i += 1
i = 0
temp_reader()
for val in rolenum:
    marks = 0 # variable to hold the Marks for the student
    while i < len:
        if val == List[i][0]:
            s, tmp = write(List[i], val)
            marks = marks + tmp

        i += 1
    s.write("\nTotal Marks is " + str(marks))   #Write the marks into the student file
    s.close()
    i = 0`enter code here`
#================================End of Code ===================================================#

创建包含学生详细信息和分数的文件的部分已经完成。但我将如何编写这样一种代码,使其对模板文件所做的更改是通用的


Tags: 文件thetotxtidforstudentlist