如何自动增加文本文件中的数字?

时间:2018-12-01 22:10:09

标签: python

我不知道我的标题是否适合我想要的用语,所以我会解释。

我的代码:

def add_new_employee():  # Creates a function named 'add_new_employee'
    with open("records.txt", "a+") as storing_records:  # Opens the record text file for append+ so that anything written to the text file will be written to the end and also so I can read the file
        last_record = records[-1]  # Creates a variable called last_record and stores the values of the records variable inside, then it gets the last value in the list.
        print("\nThe last record in the file is:\n" + last_record, "\n" + "\nPlease enter the number that comes after the previous user ID")  # Prints the last_record variable
        another_record = "y"  # Creates a variable called another_Record and sets it to 'y'
        while another_record == "y" or another_record == "Y":  # Creates a while loop that will keep running as long as the another_Record variable is set to 'y' or 'Y'
            employee_number = input("\nEnter your employee number:")  # Stores the users input in the employee_number variable
            employee_name = input("\nEnter your name:")  # Stores the users input in the employee_name variable
            employee_age = input("\nEnter your age:")  # Stores the users input in the employee_age variable
            employee_position = input("\nEnter your position:")  # Stores the users input in the employee_position variable
            employee_salary = input("\nEnter your salary:")  # Stores the users input in the employee_salary variable
            employee_years = input("\nEnter the amount of years you have been employed:")  # Stores the users input in the employee_years variable
            user_input_record = employee_number + ', ' + employee_name + ', ' + employee_age + ', ' + employee_position + ', ' + employee_salary + ', ' + employee_years  # Adds all the user inputs together and separates them with comas
            storing_records.write(user_input_record + "\n")  # Stores the user input in the records text file
            another_record = input("\n\033[33m" + "Do you want to input another record? (yes/no): " + "\033[39m").lower()  # Asks the user if they want to add another record, if the user types 'y' or 'Y' then the while loops will run again
    if another_record == 'yes':
        add_new_employee()  # If the user types anything but yes then the add_new_employee function will run
    else:
        main()  # Returns the user to the main function

我要求用户输入一个userID,但不是要求我根据文件中的先前userID自动创建它。因此,如果最后一个用户ID是023,我希望程序自动将下一个用户ID设置为024,这样用户就没有机会弄乱用户ID号的顺序了

我的textFile格式:

#EMP_NO, EMP_NAME, AGE, POSITION, SALARY, YRS_EMP   
001, Peter Smyth, 26, Developer, 29000, 4
002, Samuel Jones, 23, Developer, 24000, 1
003, Laura Stewart, 41, DevOps, 42000, 15
004, Paul Jones, 24, Analyst, 21000, 2
005, Simon Brown, 52, Developer, 53000, 18
006, George Staples, 42, Tester, 42000, 12
007, Greg Throne, 57, DevOps, 50000, 23
008, Aston Bently, 27, Tester, 33000, 5
009, Ben Evans, 32, DevOps, 38000, 2
010, Emma Samson, 23, DevOps, 22000, 1
011, Stephanie Beggs, 43, Tester, 19000, 9
012, Sarah McQuillin, 47, DevOps, 23000, 5
013, Grace Corrigan, 48, Analyst, 44000, 16
014, Simone Mills, 32, DevOps, 32000, 11
015, Martin Montgomery, 28, Analyst, 28000, 3
016, Darren Downing, 19, Developer, 24000, 5
017, Jack Campbell, 22, Designer, 20000, 2
018, Jake Peachey, 19, Designer, 20000, 4
019, Darren Downing, 19, Developer, 30000, 4
020, Jack Campbell, 21, Designer, 20090, 3
021, Darren Downing, 29, DevOps, 20000, 4
022, Megan Mckinstry, 20, Designer, 39000, 5

1 个答案:

答案 0 :(得分:0)

我写了一条评论,但我将提供一个示例,您应该可以将其集成到解决方案中以查找员工编号。

with open('example.txt', 'a+') as f:
    # Gives us the cursor position, which is currently at the end of the file, 
    # since we're using 'a+' mode
    endOfFile = f.tell()

    num_characters_to_read = 1
    num_newlines_to_ignore = 2
    initial_backward_buffer = num_characters_to_read + num_newlines_to_ignore

    # While we haven't hit the beginning of the file
    while f.tell() != 0: 
        # We traverse the file backwards and read the character at the cursor position
        f.seek(f.tell()-initial_backward_buffer)
        value = f.read(1)               

        # We know that the employee number will be at the start of the line,
        # and immediately before the previous line's newline (\n) character
        if value == '\n':
            # Get the position of the start of the line
            line_start = f.tell()
            emp_num = ""

            # And begin reading the numbers of the employee ID...
            while True:
                value = f.read(1)

                # ...and append them to our string
                if value != ',':
                    emp_num = emp_num + value
                else: # When we hit a comma, we know our "emp_num" string will contain the ID
                    break
            break # Break from the outer while loop

    # Return to the end of file, and continue from there
    f.seek(endOfFile)

    # At this point, the variable "emp_num" holds the employee ID as a string and you'll have to
    # manipulate it accordingly.

为简要说明,当我们打开文件时,我们的f是一个Python文件对象。该对象具有可以使用的some methods and functions(例如read()seek()等)。本质上,某些方法允许我们在键入时像“光标”一样使用文件对象。

当我们使用a+标志打开文件时,光标位于文件的末尾。 (这很有意义,因为如果我们要追加到文件中,则光标必须在末尾。。)在我的示例中,我使用了tell()和{{1 }“告诉”我光标所在的位置,然后向后“搜寻”或移动它,直到找到雇员编号。然后,我使用seek()函数读取每个单独的字符并将其附加到我的员工ID字符串变量中,您可以在其中将其相应地用于其余程序。