将文本文件读入字典,以便以后添加/修改/删除

2024-05-19 00:40:12 发布

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

让我先说一句,我不能百分之百肯定使用字典是否是完成这项任务的最佳方法,但我相信我需要用它来完成这项任务。你知道吗

我有一个.txt文件,格式如下:

first_name last_name rate hours
first_name last_name rate hours
first_name last_name rate hours
first_name last_name rate hours

每个项目之间只有一个空格。 每行代表一个人。你知道吗

对于我的计划,我需要能够:

  • 一次打印出所有的人
  • 能够按名字或姓氏搜索一个人并打印出他们的信息
  • 修改一个人(名字、姓氏、小时数、费率)
  • 删除某人(其所有信息)

打印出来后,我不需要查看[费率]和[小时数],而是需要查看[总工资](总工资=费率*小时数)。你知道吗

我对python的文件处理还比较陌生,所以我的第一次尝试只是读取文件中的每一行并在屏幕上打印出来,但是我遇到了能够显示[gross pay]的问题。你知道吗

# 'print_emp', display only a single employee's data chosen by the user displayed as
# firstname, lastname, grosspay (on one line of output)
def print_emp():
    menu_name = ' '*int(OFFSET/2) + "EMPLOYEE LOOKUP"
    dotted = (OFFSET+len(menu_name))*'-'

    try:
        with open('employees.txt') as file:
            print('{} \n{} \n{}'.format(dotted, menu_name, dotted))
            emp_name = input("Employee Name: ")
            print('{0:20} {1:20} {2}'.format("First Name", "Last Name", "Gross Pay"))
            for line in file:
                if emp_name in line:
                    print (line.strip())

                #print("\nEmployee", emp_name, "does not exist. Try again.\n")
                #break
    except FileNotFoundError:
        print("Error: File not found.")


# 'print_all_emp', display all employee data in format firstname, lastname,
# grosspay (on one line of output per employee)
def print_all_emps():
    menu_name = ' '*int(OFFSET/2) + "EMPLOYEE LIST"
    dotted = (OFFSET+len(menu_name))*'-'

    try:
        with open('employees.txt', 'r') as file:
            print('{} \n{} \n{}'.format(dotted, menu_name, dotted))
            print('{0:20} {1:20} {2}'.format("First Name", "Last Name", "Gross Pay"))
            for line in file:
                print(line.strip())
            print(dotted)
    except FileNotFoundError:
        print("Error: File not found.")

我不知道如何将我的.txt文件读入字典(如果我需要这样做的话),在字典中我为每个人分配一个键,其中包括他们的名字、姓氏、费率和小时数,然后乘以费率*小时数来创建工资总额,然后显示工资总额。你知道吗

我将创建三个以上的功能,我可以添加,删除和修改的人在.txt文件。你知道吗

编辑:

我相信我作为一个最终课程的目标是这样的:

https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/File_IO

但是没有加载和保存功能。。。你知道吗


Tags: 文件nametxtformatratelinefirstmenu
3条回答

通过创建Person类,可以简化一些代码。你知道吗

class Person:
    def __init__(self, first, last, rate, hours):
       self.first = first
       self.last = last
       self.rate = rate
       self.hours = hours

    def matches_name(self, name):
        return name.lower() == self.first.lower() or name.lower() == self.last.lower()

    def __str__(self):
        return '{} {} {}'.format(self.first, self.last, self.rate*self.hours)

这将简化您的代码一点。如果你想知道某人是否有特定的名字,你可以这样称呼:

a_person.matches_name(random_first_name)

如果你想打印出这个人和他们的工资总额,你只需要

print(a_person)

我认为您面临的问题是如何找到唯一的密钥
要创建唯一键,只需将所有字符串添加到一起,而不是将其散列。你知道吗

res = {}
with open('employees.txt') as file:
   for line in file:
       res[line] = line.split(' ')

假设您有空格分隔的数据,您可以只使用csv库。你知道吗

import csv

labels = ['first_name', 'last_name', 'rate', 'hours']
data = csv.DictReader(open('./test.txt'), delimiter=' ', fieldnames=labels)

result = []

for row in data:
  result.append(row)

print result

您将得到一个字典数组,每个字典都以标签作为键名。你知道吗

相关问题 更多 >

    热门问题