简体   繁体   中英

Editing one line in text file

I need an edit function, currently I have code for the user to enter an id number (same as line number) and then for writing to the certain text file, however instead of replacing the entered line, it clears the whole file and only saves the edited entry. How would I change my code so it only changes the entered line rather than deleting all the data in the file.

import time
global idnum

def number():
    global idnum
    print()
    idnum = int(input("Enter the id number of who you want to edit: "))

def edit():
    number()
    num_lines = sum(1 for line in open('Surname'))
    print()
    if idnum> num_lines or idnum ==0 or idnum < 0:
        print("Not valid")
        time.sleep(0.5)
        print("Try again")
        print()
        time.sleep(0.2)
        again()
    else:
        print()
        for file in ["Gender"]:
            with open(file) as f:
                print(f.readlines()[idnum-1], end='')

def editgender():
    with open("Gender",'r') as f:
        get_all=f.readlines()
    with open("Gender",'w') as f:
        for i,line in enumerate(get_all,1):         ## STARTS THE NUMBERING FROM 1 (by default it begins with 0)    
            if i == idnum:             
                Gender = input("Enter new gender: ")
                f.writelines(Gender + "\n")
                print("Edit saved")
                print()

Your code should be edited to look like this (at the point where the fault occurs):

if i == idnum:            
    Gender = input("Enter new gender: ")
    get_all=f.readlines()
    get_all[i-1]=Gender+"\n"
    f.write(''.join(get_all))
    print("Edit saved")
    print()

Hope this helps! :)

Try opening file with 'a' instead of 'w' mode. From python documentation:

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM