user8435959
user8435959

Reputation: 165

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()

Upvotes: 0

Views: 90

Answers (2)

fstop_22
fstop_22

Reputation: 1032

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).

Upvotes: 1

Whirlpool Pack
Whirlpool Pack

Reputation: 91

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! :)

Upvotes: 1

Related Questions