因此,我被赋予了开发员工数据库并将所有信息存储在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()
答案 0 :(得分:0)
我建议使用熊猫:
import pandas as pd
在csv文件中加载到数据框对象:
employee_df = pd.read_csv("employee_info.csv")
您可以添加新行:
name = "name"
password = "password"
email = "email@domain.com"
# depends on your columns, and the order of them!
employee_df.loc[df.index.max()+1] = [name, password, email]
然后再次将其导出到csv:
employee_df.to_csv("employee_info.csv", index=False)
答案 1 :(得分:0)
我实际上很喜欢只使用常规格式在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)