io - Keep the new line symbols in the string when writing in a text file Python -
i have list of strings, , of strings contain '\n's. want write list of strings text file , later on read , store list using readlines()
. have keep original text; meaning not removing new lines text.
if don't remove these new lines of course readlines()
return larger number of strings original list.
how can achieve this? or there's no way , should write in other formats instead. thanks.
the following:
from __future__ import print_function strings = ["asd", "sdf\n", "dfg"] open("output.txt", "w") out_file: string in strings: print(repr(string), file=out_file) open("output.txt") in_file: line in in_file: print(line.strip())
prints
'asd' 'sdf\n' 'dfg'
to print (without quotes), can use ast.literal_eval: print(ast.literal_eval(line.strip()))
Comments
Post a Comment