A
A
Arkadjan2021-11-24 22:59:27
Python
Arkadjan, 2021-11-24 22:59:27

Exporting to a text file as a table?

Help, please, to solve a problem.

Here is my code:

from prettytable import PrettyTable


def Load():
    with open ('w.txt', encoding='utf-8') as file:
        v = list(file.read().splitlines())

        d=int(v[0])

        for i in range(len(v)):
            if i == 0:
                continue
            #Фамилии
            elif i % 2 == 1:
                sd_name=''
                sd_name+=v[i]

            #Числа
            elif i % 2 == 0:
                z = v[i]
                x = int(z[0] + z[1])
                y = int(z[3] + z[4] + z[5] + z[6])

                itogo=''
                itogo+=str(x*y)

                days=''
                days+=str(x)

                oklad=''
                oklad+=str(y)

                Calc(x,y,d,sd_name,days,oklad)


summa=[]

def Calc(x,y,d,sd_name,days,oklad):
    zrplt = round(((x*y)/d), 2)
    summa.append(zrplt)
    it = sum(summa)
    Save(zrplt,sd_name,days,oklad,it)



t = PrettyTable()
t.field_names = ["Фамилия", "Дни", "Оклад", "Зарплата"]


def Save(zrplt,sd_name,days,oklad,it):
    with open('w2.txt', 'w', encoding='utf-8') as f:

        t.add_rows(
            [
                [str(sd_name),str(days),str(oklad),str(zrplt)]

            ]
        )

        t.add_row(["Итого", '','',it])
        f.write(str(t))

Load()

It turns out like this:
619e994106244472693283.jpeg
It should be like this:
619e995bdd1e5618688014.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Drill, 2021-11-26
@Arkadjan

from prettytable import PrettyTable


def data_for_table():
    with open ('w.txt', encoding='utf-8') as file:
        names, days, salaries, pays = [], [], [], []
        total = 0
        work_days, *employees = file.read().splitlines()

        work_days=int(work_days.strip())

        for elem in employees:
            if elem.strip().isalpha():
                name = f"{elem.strip():<30}"
                names.append(name)
            else:
                paid_days, salary = elem.strip().split()
                pay = float(salary)/work_days*int(paid_days)
                total += pay

                days_str = f"{paid_days:>3}"
                salary_str = f"{float(salary):>10.2f}"
                pay_str = f"{float(pay):>10.2f}"

                days.append(days_str)
                salaries.append(salary_str)
                pays.append(pay_str)

        rows = list(zip(names, days, salaries, pays))
        total_str = f"{float(total):>10.2f}"

        return rows, total_str


def table_with_footer(field_names, table_rows, table_title='', footer_field_name='', footer_field_value=''):
    pt_table = PrettyTable(padding_width=0)
    pt_table.field_names = field_names
    pt_table.add_rows(table_rows)

    if table_title:
        pt_table.title = table_title

    # Здесь используем костыль (хак?), чтобы сделать подвал таблицы (с итогами)
    # table footer
    if footer_field_name and footer_field_value:
        bottom_line = pt_table.get_string().splitlines()[-1]
        width_field_name, width_field_value = [len(line) for line in bottom_line[1:-1].rsplit('+', 1)]

        footer_fields = [f'{footer_field_name:<{width_field_name}}', f'{footer_field_value:>{width_field_value}}']

        footer_row = f'|{"|".join(footer_fields)}|'

        table_footer = (f'{footer_row}\n'
                        f'{bottom_line}')
    else:
        table_footer = ''

    # Table with title and footer
    table = (f"{pt_table.get_string()}\n"
             f"{table_footer}")

    return table



table_rows, total_value = data_for_table()

t_title = 'Зарплатная ведомость'
f_names = ["Фамилия", "Дни", "Оклад", "Зарплата"]
t_rows = table_rows
footer_f_name = "Итого"
footer_f_value = total_value

PrettyTable only:
print(table_with_footer(f_names, t_rows))

+------------------------------+---+----------+----------+
|           Фамилия            |Дни|  Оклад   | Зарплата |
+------------------------------+---+----------+----------+
|Петров                        | 15|   6300.00|   3937.50|
|Иванов                        | 24|   5600.00|   5600.00|
|Сидоров                       | 19|   4350.00|   3443.75|
|Николаев                      | 15|   4800.00|   3000.00|
|Малышев                       | 21|   4350.00|   3806.25|
|Соколов                       | 12|   7800.00|   3900.00|
+------------------------------+---+----------+----------+

Table with title and footer:
print(table_with_footer(f_names, t_rows, t_title, footer_f_name, footer_f_value))

+--------------------------------------------------------+
|                  Зарплатная ведомость                  |
+------------------------------+---+----------+----------+
|           Фамилия            |Дни|  Оклад   | Зарплата |
+------------------------------+---+----------+----------+
|Петров                        | 15|   6300.00|   3937.50|
|Иванов                        | 24|   5600.00|   5600.00|
|Сидоров                       | 19|   4350.00|   3443.75|
|Николаев                      | 15|   4800.00|   3000.00|
|Малышев                       | 21|   4350.00|   3806.25|
|Соколов                       | 12|   7800.00|   3900.00|
+------------------------------+---+----------+----------+
|Итого                                        |  23687.50|
+------------------------------+---+----------+----------+

A table with only a footer (what is in the question):
print(table_with_footer(f_names, t_rows, footer_field_name=footer_f_name, footer_field_value=footer_f_value))

+------------------------------+---+----------+----------+
|           Фамилия            |Дни|  Оклад   | Зарплата |
+------------------------------+---+----------+----------+
|Петров                        | 15|   6300.00|   3937.50|
|Иванов                        | 24|   5600.00|   5600.00|
|Сидоров                       | 19|   4350.00|   3443.75|
|Николаев                      | 15|   4800.00|   3000.00|
|Малышев                       | 21|   4350.00|   3806.25|
|Соколов                       | 12|   7800.00|   3900.00|
+------------------------------+---+----------+----------+
|Итого                                        |  23687.50|
+------------------------------+---+----------+----------+

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question