How do check for a specific character at the end of each line in a text file

Question:

I’ve written a script that appends a given character onto every line of a text file (I’m adding ',' to the end of IP addresses, one per row)

I want to prevent accidentally running the script multiple times and adding multiple of the same characters to the end of the script. i.e. adding one , is what I want, accidentally adding ten ,‘s is annoying and I’ll need to undo what I’ve done.

I’m trying to update the code to identify if the last character in a line is the same as the character that’s trying to be added and if it is, not to add it.

This code adds char to the end of each line.

file = 'test.txt' # file to append text to, keep the '' 
char = ','

newf=""
with open(file,'r') as f:
    for line in f:
        newf+=line.strip()+ char + 'n'
    f.close()

with open(file,'w') as f:
    f.write(newf)

f = open("test.txt", "r")
check = ","

And I’ve written this code to check what the last character per line is, it returns a ',' successfully for each line. What I can’t figure out is how to combine if char and check are the same value, not to append anything.

f = open("test.txt", "r")
check = ","

for line in f:
    l = line.strip()
    if l[-1:].isascii():
        check = l[-1:]
    else:
        check = 0
    print(check)

f.close()
Asked By: mak47

||

Answers:

use the endswith() function to check if it already ends with ,.

check = ","
newf = ""

with open(file) as f:
    for line in f:
        line = line.strip()
        if not line.endswith(check):
            line += check
        newf += line + "n"
Answered By: Barmar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.