python-3.x - 如何在 Python 中更新文本文件的值

标签 python-3.x text-files key-value

我想编辑/更新文本文件中的特定值。但在我的代码中,它只是将用户输入的值添加到文本文件中,根本不更新它

这是我的文本文件。它由(员工编号 Lastname, First name Position Department Birthdate Rate)组成

 123456789, Jane, Jane, Manager, ADMIN, 1/1/2000, 1000;
 332244556, Dane, John, Manager, ADMIN, 1/2/1999, 1000;
 234567890, Doe, Jane, Manager, ADMIN, 1/2/1999, 1000;

这是我的代码

def updates():
     employee_num = []
     last_name = []
     first_name = []
     emp_possition=[]
     emp_department=[]
     emp_birthdate=[]
     emp_rate = []
     with open("empRecord.txt", 'r+') as files:
         for info in files:
             info = info.strip()
             if len(info) >= 1:
                lists = info.split(',')
                employee_num.append(lists[0].strip())
                first_name.append(lists[1].strip())
                last_name.append(lists[2].strip())
                emp_possition.append(lists[3].strip())
                emp_department.append(lists[4].strip())
                emp_birthdate.append(lists[5].strip())
                emp_rate.append(lists[6].rstrip(';'))


        y = input("Enter Employee number you wish to update Records  ")
        index = employee_num.index(y)
        print('Employee', y + "'s", "Position is:", emp_possition[index])
        changes = input("Enter the new Position of the employee")
        #it just add the input and it does not change the text file
        files.write(f"{changes}")

updates()

最佳答案

changes 变量的内容已成功写入文件末尾(尽管它不包含终止换行符)。

但是,它不太可能是预期的输出。要以这种格式将修改后的数据写入文件,就需要重写文件。这是如何完成此操作的示例:

        new_position = input("Enter the new Position of the employee")

        emp_possition[index] = new_position

        files.seek(0, 0)  # go back to start
        files.truncate()

        for index in range(len(employee_num)):
            files.write("{}, {}, {}, {}, {}, {}, {};\n".format(
                employee_num[index],
                first_name[index],
                last_name[index],
                emp_possition[index],
                emp_department[index],
                emp_birthdate[index],
                emp_rate[index]))


关于python-3.x - 如何在 Python 中更新文本文件的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62116162/

相关文章:

node.js - 我应该在单个命令中增加多个键字段吗?

java - 从 ArrayList 中的 HashMap 获取键和值

python - 填写缺失的数据 Pandas

python - 有没有更简单的方法来生成一个 numpy 矩阵,其中数字垂直向上和向下加热

python - 遍历和访问 JSON 中的内部元素

php - 带分隔符的 txt 文件/字符串问题

python-3.x - Python 3 statsmodels Logit ValueError : On entry to DLASCL parameter number 5 had an illegal value

postgresql - 如何将文本文件插入 PostgreSQL 中的字段?

.net - 使用 .NET 将数据加载到 ORACLE 数据库的最快方法是什么?

java - 使用 PostgreSQL 数据库作为简单键值存储的最佳方式