Search code examples
python-3.xreplacesplitstrip

cant get rid of trailing \n when reading variable from file in python3 script


I've tried a few things but I cant get rid of \n when I print searchterm variable

1.

os.system(r"grep -R 'title' tmp2 | awk -F '\"' '{print $4}' > guessedtitle ")
with open("./guessedtitle", "r") as myfile2:
    search = str(myfile2.readlines())[2:-2]
    searchterm = ''.join(search.split())
print(searchterm)

this gives me the following output : Mr Inbetween\n

2.

with open("./guessedtitle", "r") as myfile2:
    search = str(myfile2.readlines())[2:-2]
    searchterm = str(search.replace('\r\n'))
print(searchterm)
this also give me the following output : `Mr Inbetween\n`
with open("./guessedtitle", "r") as myfile2:
    search = str(myfile2.readlines())[2:-2]
    searchterm = (search.rstrip('\r\n'))
print(searchterm)

same output : Mr Inbetween\n

please can someone guide me on what I'am doing wrong or why I am unable to remove the trailing new line?


Solution

  • You've been going about this the wrong way, that is, converting a list into a string and then trying to manipulate it is overly complicating things. Instead you can remove the trailing new line using rstrip():

    >>> s = 'Mr Inbetween\n'
    >>> s
    'Mr Inbetween\n'
    >>> s.rstrip('\n')
    'Mr Inbetween'
    

    You can process the lines of a file like this:

    os.system(r"grep -R 'title' tmp2 | awk -F '\"' '{print $4}' > guessedtitle ")
    with open("./guessedtitle", "r") as myfile2:
        for searchterm in myfile2:
            searchterm = line.rstrip('\n')
            print(searchterm)
    

    This will iterate over all the lines in the file and remove all trailing newline characters before printing the line.

    Given that you expect there to be a single line in the file, you can just use use readline() to read the single line. You would still need to remove the trailing new line.

    os.system(r"grep -R 'title' tmp2 | awk -F '\"' '{print $4}' > guessedtitle ")
    with open("./guessedtitle", "r") as myfile2:
        searchterm = myfile2.readline().rstrip('\n')
    print(searchterm)
    

    Finally, there are better ways to execute external programs from Python. The subprocess module contains functions to do that.