【问题标题】:Taking values from one file and after some calculation and a bit changes need to print into another file in python从一个文件中获取值并经过一些计算和一些更改后需要在 python 中打印到另一个文件中
【发布时间】:2021-06-13 02:45:28
【问题描述】:

下面是c.txt

CO11 CSE C1 8
CO12 ETC C1 8
CO13 Electrical C2 12
CO14 Mech E 5

我的程序需要在屏幕上打印课程摘要并将该摘要保存到文件中 命名为 cr.txt。鉴于上述 c.txt,您的程序输出应如下所示 以下。 course_report.txt 的内容也应该是一样的,除了最后一行。课程 第二列中的名称使用 * 表示必修课和 - 表示选修课 课程。第四列是该课程注册的学生人数。第五列是课程的平均分。

CID Name Points. Enrollment. Average.
----------------------------------
CO11 * CSE 8 2 81
CO12 * ETC 8 10 71
CO13 * Electrical 12 8 61
CO14 - Mech 5 4 51
----------------------------------
poor-performing subject is CO14 with an average 51.
cr.txt generated!

以下是我尝试过的:

    def read(self):
        ctype = []
        fi = open("c.txt", "r")
        l = fi.readline()
        while l != "":
            fields = l.strip().split(" ")
            self.c.append(fields)
            l = fi.readline().strip()
        f.close()
        # print(f"{'CID'}{'Name':>20}{'Points.':>16}{'Enrollment.':>18}{'Average.':>10}")
        # print("-" * 67, end="")
    print()
        for i in range(0, len(self.c)):
            for j in range(len(self.c[i])):
                obj = self.c[i][j]
                print(obj.ljust(18), end="")
        print()

    print("-" * 67, end="")
    print()

【问题讨论】:

    标签: python python-3.x list file if-statement


    【解决方案1】:

    你可以在使用'open'函数后尝试使用'file.read'或'file.readlines',如果你选择'file.readlines'你将不得不使用'for row in file.readlines()'看看我的'file.read'示例:

    headers = ['CID', 'Name', 'Points.', 'Enrollment.', 'Average.']
    compulsory_course = ['CO11', 'CO12', 'CO13']
    elective_course = ['CO14']
    count = 0
    with open('c.txt', 'r') as file_c:
        file_c.seek(0, 0)
        file_string = file_c.read().replace('\n', ' ')
        fields = file_string.split(' ')
    
    with open('cr.txt', 'w') as file_cr:
        for field in headers:
            file_cr.write(f'{field}    ')
        file_cr.write('\n')
        for v in fields:
            if count == 4:
                file_cr.write('\n')
                count = 0
            count += 1
            if v in compulsory_course:
                file_cr.write(f'{v} *    ')
                continue
            elif v in elective_course:
                file_cr.write(f'{v} -    ')
                continue
            elif count == 3:
                file_cr.write(f' ')
                continue
            file_cr.write(f'{v}    ')
    

    【讨论】:

      猜你喜欢
      • 2011-12-28
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多