Skip to main content
 首页 » 编程设计

python之Python从文件中读取数据库

2024年10月01日752php

我有一个包含 worker 全名、生日、薪水等的文件。例如,这是我的文本文件:

John Snow 1967 CEO 3400$  
Adam Brown 1954 engineer 1200$ 

我需要将此数据保存在单独的列表中以进行排序/编辑/更改/删除。我做了什么:

userFile = input('Please, enter file name, that you want to open! \n') + '.txt' 
workersData = [line.strip() for line in open(userFile, 'r')] 

我有以下输出:

['John Snow 1967 CEO 3400$', 'Adam Brown 1954 engineer 1200$'] 

我想做这样的事情:

worker1 = ['John Snow', '1967', 'CEO', '3400$'] 
worker2 = [ 'Adam Brown', '1954', 'engineer', '1200$'] 
workern = .... 

或者只是简单地调用单独的数据,例如:

name.worker1 = 'John Snow' 
salary.worker2 = '1200' 
.... 

我只是想问这在 Python 中是否可行以及如何正确实现

请您参考如下方法:

你可以使用字典:

注意:我特意没有存储workers job、workers year of birth 和workers salary 作为任务你

import os 
 
file_path = input("Please, enter the path to the file: ") 
if os.path.exists(file_path): 
    worker_dict = {} 
    k = 1 
    for line in open(file_path,'r'): 
        split_line = line.split() 
        worker = "worker%d" % k 
        worker_name = "%s_%s" % (worker, "name") 
        worker_yob = "%s_%s" % (worker, "yob") #yob stands for year of birth 
        worker_job = "%s_%s" % (worker, "job") 
        worker_salary = "%s_%s" % (worker, "salary") 
        worker_dict[worker_name] = ' '.join(split_line[0:2]) 
        # TODO: worker_dict[worker_job] = ... 
        # TODO: worker_dict[worker_yob] = ... 
        # TODO: worker_dict[worker_salary] = ... 
        k += 1 
    print(worker_dict) 
else: 
    print("Error: Invalid file path") 

输出(此时workers_dict只存储 worker 姓名):

Please, enter the path to the file: data.txt 
{'worker1_name': 'John Snow', 'worker2_name': 'Adam Brown'}