Skip to content Skip to sidebar Skip to footer

Python - Open Txt File, Remove Last Digits Of Every Line And Overwrite Old File

Is there a way in Python to read in a txt file, remove the last 6 characters of each line and overwrite the old file with the same content just without the last 6 chars on each lin

Solution 1:

You need to append the changed characters to a temporary list and then move the file pointer back to the beginning before writing again:

with open(dat, "r+") as fp:
    temp_list = []
    for line in fp:
        line = line[:-6]
        temp_list.append(line)
    fp.seek(0, 0)
    fp.write("\n".join(temp_list))

I hope this helps


Solution 2:

Try the following code, which should help you:

with open(file,'r+') as fopen:
    string = ""
    for line in fopen.readlines():
        string = string + line[:-6] + "\n"

with open(file,'w') as fopen:
    fopen.write(string)

Post a Comment for "Python - Open Txt File, Remove Last Digits Of Every Line And Overwrite Old File"