修改csv文件中的值

时间:2019-03-13 09:43:11

标签: python function csv

我正在努力进行一些项目工作,并认为有人可以在这里为我提供帮助。我正在编写一个数据库工具,需要能够从某人的csv文件中找到一个ID值,并将其雇员状态从有效更改为无效。拥有非常基本的python知识,我为此感到吃力。这是我现在可以使用的代码。

def menu():
  print("Welcome to the Employee database\n")
  print("1. Add a new employee\n")
  print("2. Remove an existing employee\n")
  print("3. Change/modify the details of an existing employee\n")
  print("4. Search and display the details for a particular employee\n")
  print("0. Quit\n")

  choice = int(input("Please select an option using the numbers above"))
  if choice == 0:
     return
  if choice == 1:
     add()
  if choice == 2:
     remove()
  if choice == 3:
     change()
  if choice == 4:
     search()

def add():
  print("Adding a new employee, please enter the following details\n")
  employee_id = int(input("Enter your employee ID\n"))
  name = input("Enter your name\n")
  department = input("Enter your department\n")
  designation = input("Enter your designation\n")
  joining_date = input("Enter your starting date [DD/MM/YYYY]\n")
  employee_status = input("Enter the employee status [Active/Inactive]\n")

  with open('database.csv', "a") as f:
     employee_info = ""
     employee_info += "%s," % employee_id
     employee_info += "%s," % name
     employee_info += "%s," % department
     employee_info += "%s," % designation
     employee_info += "%s," % joining_date
     employee_info += "%s," % employee_status
     employee_info += "\n"
     f.write(employee_info)
 menu()

我需要它能够接收想要使其无效的ID用户输入,在csv中找到合适的人并将其标签更改为无效。这可能吗?

我将不胜感激!

编辑:

这是csv文件的内容:

Employee ID,Name,Department,Designation,Joining Date,Employee Status
456,Matt,IT,Data,02/04/2018,Active
245,John,HR,Manager,30/04/2019,Active

4 个答案:

答案 0 :(得分:0)

我只有两美分。我想,使用ini文件会更容易使用。

[ID4711]
name = Person A
status = ACTIVE

[ID4712]
name = Person B
status = ACTIVE

[ID4713]
name = Person C
status = INACTIVE

代码

import configparser

config = configparser.ConfigParser()
config.read('default.ini')
print(config['ID4711']['NAME'])
print(config['ID4711']['STATUS'])

config['ID4711']['STATUS'] = 'TEST'

with open('default.ini', 'w') as configfile:
    config.write(configfile)

答案 1 :(得分:0)

您可以使用pandas库。

首先,您需要导入pandas并读取csv文件。

import pandas as pd
df = pd.read('/path/to/csv_file')

由于每个员工都有唯一的员工ID,因此您可以使用loc方法来更改值。

df.loc[df["Employee ID"]==12345, "Employee Status"] = "Inactive"

完成更改后,将其保存回csv文件。

df.to_csv("/path/to/csv_file", index=False)

检查此堆栈Change specific value in CSV file via Python

答案 2 :(得分:0)

csv文件是顺序文本文件。这是一种非常不错的交换格式,因为它不依赖于任何物理系统。但是更改其中的一个值最终会更改文本文件中的一个值。并且,除非您确定新值的大小与原始值的大小完全相同(并且ActiveInactive的大小不同...),否则唯一可靠的方法是重写整个值文件。

您可以将所有内容加载到内存中,也可以复制到临时文件以更改特定行,然后将临时文件重命名为原始名称。您应该在SO中找到相关示例:

顺便说一句,如果它是一个csv文件,则使用csv模块可能会有用...

答案 3 :(得分:0)

最简单的方法:

import csv

def menu():
  print("Welcome to the Employee database\n")
  print("1. Add a new employee\n")
  print("2. Remove an existing employee\n")
  print("3. Change/modify the details of an existing employee\n")
  print("4. Search and display the details for a particular employee\n")
  print("5. Inactive Employee\n")
  print("0. Quit\n")

  choice = int(input("Please select an option using the numbers above"))
  if choice == 0:
     return
  if choice == 1:
     add()
  if choice == 2:
     remove()
  if choice == 3:
     change()
  if choice == 4:
     search()
  if choice == 5:
     inactive()

def add():
  print("Adding a new employee, please enter the following details\n")
  employee_id = int(input("Enter your employee ID\n"))
  name = input("Enter your name\n")
  department = input("Enter your department\n")
  designation = input("Enter your designation\n")
  joining_date = input("Enter your starting date [DD/MM/YYYY]\n")
  employee_status = input("Enter the employee status [Active/Inactive]\n")

  with open('database.csv', "a") as f:
     employee_info = ""
     employee_info += "%s," % employee_id
     employee_info += "%s," % name
     employee_info += "%s," % department
     employee_info += "%s," % designation
     employee_info += "%s," % joining_date
     employee_info += "%s," % employee_status
     employee_info += "\n"
     f.write(employee_info)


def inactive():
    print("Inactive Employee\n")
     employee_to_inactive = int(input("Enter your employee ID\n"))

     with open('database.csv', "r") as csv_file:
         csv_reader = csv.reader(csv_file, delimiter=',')
         full_list = list(csv_reader)

         rows = []
         rows.append(full_list[0])
         for item in range(1, len(full_list)):
             if int(full_list[item][0]) == employee_to_inactive:
                 full_list[item][5] = "Inactivate"
             rows.append(full_list[item])

     with open('database.csv', 'w') as f:
         writer = csv.writer(f, delimiter=',')
         writer.writerows(rows)



menu()