gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:52 26 4
gpt4 key购买 nike

我有一个包含 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 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只存储 worker 姓名):

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

关于python - Python从文件中读取数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42714541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com