从Python中的文件读取数据库

时间:2017-03-10 09:17:42

标签: python list-comprehension

我有一个工人全名,生日,工资等文件。例如,这是我的文本文件:

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中以及如何正确使用

2 个答案:

答案 0 :(得分:1)

你可以使用字典:

注意:我故意不将workers jobworkers year of birthworkers 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仅存储此时的工作人员姓名):

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

答案 1 :(得分:1)

这将完成你的工作

data = ['John Snow 1967 CEO 3400$', 'Adam Brown 1954 engineer 1200$']
all_workers = []
temp = []
for item in data:
    temp = item.split(" ")
    worker = []
    worker.append(temp[0] + " " + temp[1])
    worker.append(temp[2])
    worker.append(temp[3])
    worker.append(temp[4])
    all_workers.append(worker)
print all_workers

输出:

  

[[' John Snow',' 1967',' CEO',' 3400 $'],['亚当布朗',' 1954',   ' engineer',' 1200 $']]