Convert strings to a convenient Excel format

I have a line of text. A line contains several newline characters. I want to create a csv that includes this line, so I can import it into excel. However, because of this, I believe that I need to convert all newlines to carriage returns and wrap the text in quotation marks.

However, when I try to convert a small amount of text, I get the following results:

Before

>>> abc = "\nA\nB\nC\nD\nE\nF\nG\n\n" >>> print abc A B C D E F G 

After

 >>> xyz = abc.replace('\n','\r') >>> xyz '\rA\rB\rC\rD\rE\rF\rG\r\r' >>> print xyz G 

Any ideas what I'm doing wrong?

+4
source share
3 answers

Use the Python csv module , which already knows how to do this.

 import csv with open('xyz.csv', 'wb') as outfile: w = csv.writer(outfile) w.writerow(['a\nb\nc']) 

After starting this process, you can check the output ( -A , on cat GNU, shows a representation of non-printable characters):

 $ cat -A xyz.csv "a$ b$ c"^M$ 

Note that you can also use cat -A to understand why your previous implementation turned out to be wrong.

+4
source

Try to write this line to a file and look at it in a text editor.

Your console interprets the carriage return as โ€œreturning to the beginning of the line,โ€ so print A, then print B, where A is, etc., until G prints where F.

+3
source

Using:

 xyz = abc.replace('\n','\r\n') 
0
source

Source: https://habr.com/ru/post/1487900/


All Articles