-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) 
4
  • Can you try passing the newline='' parameter in the open() function? Commented Feb 18, 2020 at 21:26
  • Does this answer your question? Specify Newline character ('\n') in reading csv using Python Commented Feb 18, 2020 at 21:27
  • 1
    What did you expect instead? Commented Feb 18, 2020 at 21:49
  • How is the one line in the csv file supposed to be interpreted? Commented Feb 18, 2020 at 22:09

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that's what I needed!
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') 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.