Home > OS >  Replace first x characters in line in text file
Replace first x characters in line in text file

Time:10-02

I have a text file of information in format "number, lastname, firstname, age,"

1,Lname1,Fname1,Age,
2,Lname2,Fname2,Age,
3,Lname3,Fname3,Age,
4,Lname4,Fname4,Age,
5,Lname5,Fname5,Age,
6,Lname6,Fname6,Age,
7,Lname7,Fname7,Age,
8,Lname8,Fname8,Age,
9,Lname9,Fname9,Age,
10,Lname10,Fname10,Age,
11,Lname11,Fname11,Age,

and I have a function set up to remove a line from this list. This would mean the first number is not equal to the line number, which is an issue.

Right now i have this to fix:

def line_restructure():                                                                                                 
with open("Student_Directory.txt", "r") as f:                                                                       
    x = 1                                     #Sets starting line to 1                                                           
    output = []
    for line in f:
        new = str(x)   line[1:]               #Replaces first character in line with X
        output.append(new)                    #Adds new string with replacement to output list
        x  = 1                                #X becomes next line number
with open("Student_Directory.txt", "w") as f:
    f.writelines(output)                      #Rewrites file with same information
                                              #but first character == line number

but because of string splicing, this only works for the first 9 lines, because after that the first number is two digits, thus it will cause the 10th and 11th entry in the list above to become:

100,Lname10,Fname10,Age,
111,Lname11,Fname11,Age,

I just want it to rewrite the file keeping exact same information and formatting, but changing the first number to == the line number.

CodePudding user response:

Rather than trimming a fixed amount of characters from the beginning of the line, you can trim up to the first comma:

def line_restructure():                                                                                                 
    with open("Student_Directory.txt", "r") as f:                                                                       
        x = 1                                     #Sets starting line to 1                                                           
    output = []
    for line in f:
        index_of_comma = line.index(",")
        new = str(x)   line[index_of_comma:]  #Replaces portion of line up to first comma with X
        output.append(new)                    #Adds new string with replacement to output list
        x  = 1                                #X becomes next line number

with open("Student_Directory.txt", "w") as f:
    f.writelines(output)                      #Rewrites file with same information
                                              #but first character == line number
  • Related