0

I want to make a switch case.If option 1 is pressed then some info is added to a csv file and after exit the case if again run the code and choose option 2 then it search some text in file and if found then add something to it.

I have tried the code given below.It runs option 1 correct but give errors in option 2.

from datetime import datetime
import fileinput

today = datetime.now()
In = str(today.strftime("%d/%m/%Y , %H:%M:%S"))
In1=In.rpartition(' , ')[0]
today = datetime.now()
Out = str(today.strftime("%d/%m/%Y , %H:%M:%S"))
out1=Out.rpartition(' , ')[2]
name=input("enter name of employee: ")
attend1=name+" , "+In1
f = open("Attend.csv", "a")
filename="Attend.csv"
while True:
    print("1. Enter In Time\n2. Enter Out Time")
    choice=input("Enter your choice: ")
    if choice == "1":
        attend = name+" , "+In
        print(attend)
        f.write(attend+"\n")
    elif choice == "2":
        attend = name+" , "+Out
        print(attend)
        f = open("Attend.csv", "r+")
        for lines in f:
            if attend1 in lines:
                lines=lines.replace(lines,lines+" , "+out1)
            f.write(lines+"\n")
     else:
        print("Please choose the correct entry.")
        break
f.close()
mahi chauhan
  • 49
  • 2
  • 9
  • What are you trying to do here, could you give us more details? I guess you are trying to keep record of when employees start and end their journey. Why are you taking the time just at the begining? – palvarez Jul 19 '19 at 14:37

1 Answers1

0

The first case is easy, since it is just adding a line to the end of file. The second case is not working because you are just adding the time at the end, without strip the line and not searching for your line to be modified.

There is a problem in case the out time was added in the same iteration as the in, that means the file modification is not visible until you close the file, so you wouldn't find the in register.

By using this answer on how to search and replace a line in a file I came up with this:

from datetime import datetime
from os import fdopen, remove
from tempfile import mkstemp
from shutil import move

def end_employee_day(filename, employee, end_time):
    updated = False
    #Create temp file
    temp, abs_path = mkstemp()
    with fdopen(temp,'w') as new_file:
        with open(filename) as old_file:
            for line in old_file:
                # Search for employee in register
                if line.startswith(employee) and len(line.split(" , ")) == 3:
                    if updated:
                        print(f"Multiple in register found for {employee}")
                    updated = True
                    line = f"{line.strip()} , {end_time}\n"
                    print(line)
                new_file.write(line)
    #Remove original file
    remove(filename)
    #Move new file
    move(abs_path, filename)
    if not updated:
        print(f"In register not found for {employee}")

filename = "Attend.csv"
today = datetime.now
while True:
    print("1. Enter In Time\n2. Enter Out Time")
    choice = input("Enter your choice: ")
    if choice not in ("1", "2"):
        print("Quitting")
        break
    name = input("enter name of employee: ")
    if choice == "1":
        with open(filename, "a") as f:
          now_time = str(today().strftime("%d/%m/%Y , %H:%M:%S"))
          attend = f"{name} , {now_time}\n"
          print(attend)
          f.write(attend)
    elif choice == "2":
        now_time = str(today().strftime("%H:%M:%S"))
        end_employee_day(filename, name, now_time)

This allows to add registers of multiple employees in the same run. I did this since it seemed a little weird for me to add the in and out times for the same employee at the same time.

This code does not keep you from entering multiple in registers of the same employee without having registered the out time. The out time will be added to all in registers it finds.

Hope it helps, do not hesiste if you have any questions.

palvarez
  • 1,508
  • 2
  • 8
  • 18
  • thanks for your help.I am unable to understand one line. i.e. line = f"{line.strip()} , {end_time}\n" – mahi chauhan Jul 23 '19 at 07:15
  • You could check out the docs about [formatted string literals](https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals) or f-strings, which are introduced in Python 3. Short story, f-string allows you to replace expressions evaluated at runtime on strings. – palvarez Jul 23 '19 at 08:07