python - 在 python 中进行文件操作的 Pickel 和 CSV 的替代品
问题描述
所以我被赋予了开发员工数据库并将所有信息存储在 CSV 文件中的任务。添加信息后,我需要用于删除、编辑和搜索所述数据的可用选项。它是我能导入和不能导入的灰色区域,所以如果有一种方法不使用移植,那将是完美的。基本上,只要使用 read() 和 write() 就可以了。
但是,无论我做什么,我都无法在网上找到有关如何以可用格式实际提取这些特定数据的帮助。下面是我如何将它添加到 CSV 文件中,但无论我尝试什么,我最终都会擦除文件或在尝试删除过程时出现错误。希望每当我能找到一种方法来提取这些数据时,编辑和搜索功能将只是一个逻辑案例。
(我的添加功能)
def add_employee(): #THIS WORKS
EmployeeID = int(input("Please enter the employee ID here "))
EmployeeName = input("Please enter the name here ")
EmployeeDep = input("Please enter the department here ")
EmployeeDes = input("Please enter the designation here ")
EmployeeStartDate = input("Please enter the start date here in format of DD-MM-YYYY ")
EmployeeStatus = input("Please enter the status here ")
with open('database.csv', "a") as f:
employee_add = ""
employee_add += "%s," % EmployeeID
employee_add += "%s," % EmployeeName
employee_add += "%s," % EmployeeDep
employee_add += "%s," % EmployeeDes
employee_add += "%s," % EmployeeStartDate
employee_add += "%s," % EmployeeStatus
employee_add += "\n"
f.write(employee_add)
print("Added correctly")
continue_or_quit()
解决方案
实际上,我非常喜欢仅使用常规格式在 python 中使用 csv。
像:
rows = content.split("\n") # get the rows (content in this example would be result of .read()
for row in rows:
values = row.split(",") # get row values
要根据您的示例添加一行,您可以使用以下内容:
row = "{},{},{},{},{},{}\n".format(EmployeeID, EmployeeName, EmployeeDep, EmployeeDes, EmployeeStartDate, EmployeeStatus)
with open(output, "a") as f:
f.write(row)