python 如何永久更改文本文件的值?

bxjv4tth  于 2023-02-18  发布在  Python
关注(0)|答案(2)|浏览(140)

我相当新的处理文件,所以我只是困惑

#pretend this is a text file, do not modify this part of the code.....
emps='''20120001;Tortor;Griffin;Manager;Admin;1000;5000
20120002;Sebastian;Jest;Assist. Manager;Admin;750;3000'''

f = open('empList.txt','w')
f.write(emps)
f.close()

#Code here
employees = []
while True:
    print('''1 - Show Employees
2 - Increase Salary to employees
X - Exit
    ''')
    choice = input('Enter your choice: ')
    print()
    if choice =='2':
        with open('empList.txt', 'r') as f:
            employees = f.read().splitlines()
        for employee in employees:
            emp_num, last, first, position, dept, salary, allowance = employee.split(';')
            if position == 'Manager':
                print(f'{emp_num} {last} {first} {float(salary)*2} {dept} {allowance} {position}')
            else:
                print(f'{emp_num} {last} {first} {float(salary)*1.5} {dept} {allowance} {position}')
        print()
    elif choice =='1':
        with open('empList.txt', 'r') as f:
            employees = f.read().splitlines()
        for employee in employees:
            emp_num, last, first, position, dept, salary, allowance = employee.split(';')
            print(f'{emp_num} {last} {first} {float(salary)} {dept} {allowance} {position}')
        print()
    elif choice =='X':
        break

我的问题是每当我输入选项2时,薪金的更改值不是永久的,因此每当我通过输入选项2更改值时,它仍然显示未更改的值,我如何解决此问题?
可能是因为我用了一个print语句,但是我不知道应该用什么函数,我想用append,但是它只会复制数据,我错过了什么?
所以这就是问题所在。

bvhaajcl

bvhaajcl1#

首先,你用'r'打开文件,它是只读模式,你需要把它改成'w',比如:with open('empList.txt', 'w').
第二件事是你没有写任何东西到文件中,你只是打印它。你在选择中错过了f.write(...)

tyu7yeag

tyu7yeag2#

你可以创建一个新数据的副本,然后使用write()函数将其写回文件,如下所示。注意,代码没有经过测试,但该方法应该有助于你找到解决方案。

if choice =='2':
    with open('empList.txt', 'r') as f:
        employees = f.read().splitlines()
    # create a new list to store modified employee data
    modified_employees = []
    for employee in employees:
        emp_num, last, first, position, dept, salary, allowance = employee.split(';')
        if position == 'Manager':
            # Append current employee record with modified salary to the new list
            modified_employees.append("{};{};{};{};{};{};{}".format(emp_num, last, first, position, dept, salary*2, allowance))
            print(f'{emp_num} {last} {first} {float(salary)*2} {dept} {allowance} {position}')
        else:
            # Append current employee record with modified salary to the new list
            modified_employees.append("{};{};{};{};{};{};{}".format(emp_num, last, first, position, dept, salary*1.5, allowance))
            print(f'{emp_num} {last} {first} {float(salary)*1.5} {dept} {allowance} {position}')
    # Write the new list back to file. This will overwrite previous content and keeps the fresh
    with open('empList.txt', 'w') as f:
        for each_record in modified_employees:
            f.write("{}\n".format(each_record))

相关问题