Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify new lines on Python, when writing on files?

In comparison to Java (in a string), you would do something like "First Line\r\nSecond Line".

So how would you do that in Python, for purposes of writing multiple lines to a regular file?

like image 530
FabianCook Avatar asked Jul 16 '12 02:07

FabianCook


People also ask

How do you write to the next line in Python file handling?

Append Data to a New Line Using a New Line Character ( \n ) in Python. A new line is represented using a new line character or \n in programming languages such as Python or C++. While appending or adding new data to a file, we can add this character at the end of each line to add new data to a new line.

How do you write on different lines in Python?

You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line. In the revised version of the script, a blank space and an underscore indicate that the statement that was started on line 1 is continued on line 2.

How do you skip to the next line in a text file in Python?

how to make a python text skip a line break? The new line character is “\n”. It is used inside of a string.


1 Answers

It depends on how correct you want to be. \n will usually do the job. If you really want to get it right, you look up the newline character in the os package. (It's actually called linesep.)

Note: when writing to files using the Python API, do not use the os.linesep. Just use \n; Python automatically translates that to the proper newline character for your platform.

like image 136
Charlie Martin Avatar answered Sep 28 '22 03:09

Charlie Martin