Modifying a value from a csv file

how to update data in csv file using python
python csv find and replace
how to replace a word in csv file using python
python replace values in csv column
python csv replace column
python csv update cell
python change values in csv column
csv reader

I'm struggling with some project work and thought someone may be able to help me here. I am writing a database tool, and need to be able to find an ID value from a person on a csv file, and edit their employee status from active to inactive. Having very basic python knowledge, I am struggling with this. Here is my code that is working now.

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()

I need it to be able to take an input from the user of the ID they want to make inactive, find the right person in the csv and change their tag to inactive. Is this possible?

I would appreciate any help whatsoever!

Edit:

Here is the csv file contents:

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

The easiest way:

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()

PowerShell: Change Values in CSV Data, For example, you have imported user account data from a CSV file that uses an AD account's samAccountName as a unique value for each row� A Comma Separated Values file might sometimes be referred to as a Character Separated Values or Comma Delimited file, but regardless of how someone says it, they're talking about the same CSV format. CSV is also an acronym for comma separated variable , circuit switched voice , and colon separated value .

Just my two cents. I guess, using an ini file would be easier to use.

[ID4711]
name = Person A
status = ACTIVE

[ID4712]
name = Person B
status = ACTIVE

[ID4713]
name = Person C
status = INACTIVE

Code

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)

Change record values to blank or null with Data Loader, By default, Data Loader will treat any blank cells in your CSV file as though no change is needed for that field. If you'd like to use Data Loader to remove the� When working with multi-dimensional arrays like imported CSV data, sometimes you want to change one or more values in one of the rows. For example, you have imported user account data from a CSV file that uses an AD account’s samAccountName as a unique value for each row.

You can use pandas library.

First you need to import pandas and read the csv file.

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

Since every Employee will be having a unique Employee ID, you can use loc method to change the value.

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

After doing the changes, save it back to the csv file.

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

Check this stack Change specific value in CSV file via Python

How to create, read, update and search through Excel files using , A CSV file is a comma-separated values file, where plain text data is The next step is to modify the writer function so it creates a file that holds� To view a CSV file in Notepad++ after installing it, right-click the CSV file and select the “Edit With Notepad++” command. You’ll see the plaintext list of data in the CSV file. For example, if the CSV file was exported from a contacts program, you’d see information about each contact here, with the contact’s details sorted onto a

Files with delimiter-separated values - Help, Files with delimiter-separated values. Last modified: 08 May 2020. AppCode lets you edit delimited text files (CSV, TSV, and other delimiter-separated formats)� Let’s begin with a simple, yet worthy CSV file as an example. In the below CSV data, we have four columns, fields, or properties — whatever you want to call them at this point. They are Name, Status, BatchName, and SentNotification.

Update a csv column value using input parameter as row and , Is there any method in Apache-csv to change the value of file based on the Use the CSVParser class to read the records and the CSVPrinter to write The documentation at org.apache.commons:commons-csv:1.7 api doc� Okay, I suppose evilness isn’t really a property of CSV files, but if you’ve ever wrestled with a bad one, I think you know what I mean. Since you're now aware that CSV (comma separated value) files are superior to delimited files for data importing, let’s talk about how to create a CSV file. Here are the rules for creating CSV files:

How do I use a CSV file to store variables for scenario parameters?, This article provides details on using a CSV file for parameterizing your data. unlimited rows of data values, stored in comma separated values (CSV) files, the file in CSV format, use the editor's Save As option and change the Save as type� Data from the .csv file is then imported into the dataset in Power BI. Power BI then automatically connects to the file and refreshes any changes with the dataset in Power BI. If you edit the .csv file in OneDrive, or SharePoint Online, once you save, those changes will appear in Power BI, usually within about an hour.

Changing CSV layer attribute value from text to number in QGIS , I once had the same question. The answer is that you put a file in the same folder with the ending csvt. For example your file name is xyzdata.csv you add the file� Filtering CSV file. It is possible to filter out or modify some of the rows in the CSV file before passing the data to the transformation. The filter can be set when configuring CSV format. The technique is explained here. Available objects and methods. The actual filtering is performed by an object, which can be referenced as a filter.

Comments
  • No problem, to do it with a csv file, but why not using sqllite db or ini file?
  • Can you please add the structure of the csv file contents?.
  • @bumblebee added them :)
  • @Xenobiologist because I just don't know how to, I'm still very new to programming so the whole process has been quite daunting.
  • I think you might find this answer useful. You could add a save() method to the DataBase class that rewrote the input file.
  • hey, thanks for your help! This already seems a lot more simpler and at my level of understanding. One thing, I tried running the code and got an error when inputting an ID. It was "ValueError: invalid literal for int() with base 10: 'Employee ID'"
  • Try it again. I changed it.
  • thank you so much!! works exactly as I wanted, I really appreciate it!
  • Using pandas only to change a value in a csv file is overkill!
  • Yes, it is, that's why I have added a stack where they have provided more than one approach. I found pandas easier.