-2

Im reading strings from a csv file. These strings contain "\n" chars to represent new lines. How can I print these strings with the correct new lines? Using str() didn't work.

CSV File has only one line:

Dest, Test\n Test2\n Test3

The code below prints Test\n Test2\n Test3

for ifile in files:
    with open(orderPath + '\\' + ifile) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')

        for row in csv_reader:

            dest = row[0]
            message = row[1]

            message = str(message)
            print(message)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
YvesN
  • 3
  • 2

2 Answers2

1

It's unclear precisely how you want the data in the csv file to be interpreted, but here's a guess. It uses the ast.literal_eval() function to convert the escape characters in the input data into newline characters.

This involves enclosing the second column in triple double-quotes (""") characters to allow it to interpreted as Python string literal. Triple quotes are used in case the enclosed text itself contains quotes. For example: Dest, Test\n "Test2"\n Test3

import ast
import csv

filename = 'one_line.csv'

with open(filename, newline='') as csv_file:
    for row in csv.reader(csv_file, delimiter=','):
        dest = row[0]
        message = ast.literal_eval('"""{}"""'.format(row[1]))
        print(dest)
        print(message)

Output:

Dest
 Test
 Test2
 Test3
martineau
  • 119,623
  • 25
  • 170
  • 301
0

If I understand correctly, you want to replace the sequence of literal characters '\' and 'n' in your input with newlines:

Instead of:

message = str(message)

You want:

message = message.replace('\\n', '\n')
JBGreen
  • 534
  • 2
  • 6