So this is probably a stupid question but it is annoying and bothering me and I cannot seem to find the answer googling. Why when reading and then printing from a csv file does \n get printed as \n and not become a newline?
Asked
Active
Viewed 117 times
0
-
Are you printing the `list`s `csv.reader` is returning directly? It should be removing newlines as part of the parsing if they're not embedded in a field, but `list`s print the `repr` of their contents, and the `repr` of `str` is quoted and uses escapes for the various types of whitespace (aside from the space character itself). – ShadowRanger Oct 15 '21 at 03:39
-
I am storing the line of csv.reader in a variable and printing variable[0]. So if my csvfile has a\na it prints out a\na exactly like that. – GSGregory Oct 15 '21 at 03:47
-
1Please edit the question to include a [MCVE]; it shouldn't do what you describe (unless the file contains a literal backslash followed by n in the first field, so be sure to include a little sample data too), but your description could be less accurate than the actual code. – ShadowRanger Oct 15 '21 at 04:16
1 Answers
0
Try decoding the literal string/bytestring wiht something like:
my_string = r"asdasd\nasdaasd"
print(my_string)
print(bytes(my_string, "utf-8").decode("unicode_escape"))
Check for more: Process escape sequences in a string in Python

Tzane
- 2,752
- 1
- 10
- 21