remove \n from a line in python

1.1k Views Asked by At

I have a txt file that I need to convert into a table. If I have a case like this:

---------------------------------------------
|apple|very good|every day|fruit
|chocolate|not so good|just\n
some times|snack
|bread|good|every day|whole|carbs
---------------------------------------

I splitted the file on the '|' but the new line is a problem I cannot overcome, how can I join the two lines?

with open("ridotto.txt", encoding='latin-1') as f:     
    new_list=[]
    for line in f:
        if line.startswith("-"):
            line.replace("-", "")
        else:
            new_list.append(line.replace('\n', ' ').split('|'))

When I do this I get as a result:

[apple,very good,every day,fruit,chocolate, not so good, just ,some times, snack,bread, good, every day, whole, carbs]

while I want just some times to be one singular element Note: the \n is not literal

5

There are 5 best solutions below

0
Rajesh Kanna On

Sometimes the \n is actually \r\n under the hood

try this if it helps

new_list.append(line.replace('\n', ' ').replace('\r\n', ' ').split('|'))
0
David On

If you are trying to remove a literal newline, then just use two backslashes: replace('\\n', ' '). Python uses the backslash as an escape character and so you have to escape the backslash itself if you want to use a literal backslash.

0
Null On

for your code, I recommend you to do this

with open("ridotto.txt", encoding="latin-1") as f:
    new_list = []
    for line in f:
        if "\\n" in line:
            new_list.append(line.replace("\\n\n", "").split("|"))
        elif not line.startswith("-"):
            new_list.append(line.replace("\n", "").split("|"))
2
Bhargav - Retarded Skills On

Read text file. & replace items one by one accordingly.

with open('text.txt', 'r') as file:
    data = file.read().replace('\n', '')

data = data.replace("\\n", " ")
data = data.replace("-", " ")
data = data.strip()
my_list = data.split("|")
my_list = [i for i in my_list if i]  # Remove empty elements

print(my_list)

Gives #

['apple', 'very good', 'every day', 'fruit', 'chocolate', 'not so good', 'just some times', 'snack', 'bread', 'good', 'every day', 'whole', 'carbs']
0
SoulSeeke On

Maybe the following logic might help you, if what you want is to combine 2 lines, when the first line ends with \n in the file

from io import StringIO

with open("ridotto.txt", encoding='latin-1') as f:     
    new_list=[]
    
    ## if there is \n in end of text line, then remove the newline character on that line ##
    c = f.read().replace("\\n\n",' ')
    
    ## Reading string like a file ##
    with StringIO(c) as file: 
        for line in file:
            if line.startswith("-"):
                continue
            else:
                new_list.append(line.replace('\n', '').split('|'))