python中用于文件操作的Pickel和CSV的替代方法

2024-05-08 22:18:54 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我被分配了一项任务,开发一个员工数据库,并将所有信息存储在一个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()

Tags: 文件csvthe数据方法功能add信息
2条回答

实际上,我非常喜欢在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)

我推荐使用熊猫:

import pandas as pd

将csv文件加载到dataframe对象: 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)

相关问题 更多 >