如何在python文件中找到某些文本之后添加文本?​​

时间:2019-07-19 11:07:39

标签: python-3.x

我想制作一个开关盒。如果按下选项1,则将一些信息添加到一个csv文件中,退出后,如果再次运行该代码并选择选项2,则它将在文件中搜索一些文本,如果找到则向其中添加一些东西。

我尝试了下面给出的代码。它正确运行选项1,但在选项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()

1 个答案:

答案 0 :(得分:0)

第一种情况很简单,因为它只是在文件末尾添加了一行。第二种情况不起作用,因为您只是在末尾添加时间,没有 strip行,也没有搜索要修改的行。

如果在与out相同的迭代中添加了in时间,则意味着在关闭文件之前看不到文件修改,因此无法找到文件,这是一个问题in寄存器。

通过在how to search and replace a line in a file上使用此答案,我想到了:

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)

这允许在同一运行中添加多个员工的登记册。我这样做是因为对同一位员工同时添加inout时间似乎有点奇怪。

此代码不会阻止您在未注册in时间的情况下输入同一员工的多个out寄存器。 out时间将添加到找到的所有in寄存器中。

希望有帮助,如有任何疑问,请不要犹豫。