Yura
Yura

Reputation: 63

Reading database from a file in Python

I have a file with full names of workers, birthday, salary etc. For example, this is my text file:

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

I need to save this data in separate lists to sort/edit/change/delete. What I have done:

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

I have the following output:

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

I want to make something like this:

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

Or just simply call separate data like:

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

I'm just asking if this possible in Python and how to make it correctly

Upvotes: 2

Views: 100

Answers (2)

SHAHS
SHAHS

Reputation: 472

This will do your work

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

Output:

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

Upvotes: 1

Sash Sinha
Sash Sinha

Reputation: 22370

You could use a dictionary:

Note: I have purposely left out storing the workers job, workers year of birth and workers salary as a task for you

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")

Output (workers_dict only stores the workers name at this point):

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

Upvotes: 1

Related Questions