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

☆樱花仙子☆ 提交于 2019-11-26 05:57:23

问题


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 on a regular file?


回答1:


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.




回答2:


The new line character is \n. It is used inside a string.

Example:

    print 'First line \n Second line' 

where \n is the newline character.

This would yield the result:

First line
 Second line



回答3:


You can either write in the new lines separately or within a single string, which is easier.

Example 1

Input

line1 = "hello how are you"
line2 = "I am testing the new line escape sequence"
line3 = "this seems to work"

You can write the '\n' separately:

file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.write("\n")

Output

hello how are you
I am testing the new line escape sequence
this seems to work

Example 2

Input

As others have pointed out in the previous answers, place the \n at the relevant points in your string:

line = "hello how are you\nI am testing the new line escape sequence\nthis seems to work"

file.write(line)

Output

hello how are you
I am testing the new line escape sequence
this seems to work



回答4:


In Python you can just use the new-line character, i.e. \n




回答5:


If you are entering several lines of text at once, I find this to be the most readable format.

file.write("\
Life's but a walking shadow, a poor player\n\
That struts and frets his hour upon the stage\n\
And then is heard no more: it is a tale\n\
Told by an idiot, full of sound and fury,\n\
Signifying nothing.\n\
")

The \ at the end of each line escapes the new line (which would cause an error).




回答6:


Simplest solution

If you only call print without any arguments, it will output a blank line.

print

You can pipe the output to a file like this (considering your example):

f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close()

Not only is it OS-agnostic (without even having to use the os package), it's also more readable than putting \n within strings.

Explanation

The print() function has an optional keyword argument for the end of the string, called end, which defaults to the OS's newline character, for eg. \n. So, when you're calling print('hello'), Python is actually printing 'hello' + '\n'. Which means that when you're calling just print without any arguments, it's actually printing '' + '\n', which results in a newline.

Alternative

Use multi-line strings.

s = """First line
    Second line
    Third line"""
f = open('out.txt', 'w')
print s >> f
f.close()



回答7:


The same way with '\n', though you'd probably not need the '\r'. Is there a reason you have it in your Java version? If you do need/want it, you can use it in the same way in Python too.




回答8:


\n - simple newline character insertion works :

# Here's the test example - string with newline char :
In [36]: test_line = "Hi!!!\n testing first line.. \n testing second line.. \n and third line....."

# Output:
In [37]: print(test_line)

Hi!!!
 testing first line.. 
 testing second line.. 
 and third line.....



回答9:


Most escape characters in string literals from Java are also valid in Python, such as "\r", "\n"




回答10:


\n separates the lines of a string. In the following example I'm keep on writing the records in a loop. Each record is separated by \n

f = open("jsonFile.txt", "w")
for row_index in range(2,sheet.nrows):

  mydict1 = {
    "PowerMeterId" : row_index + 1,
    "Service": "Electricity",
    "Building": "JTC FoodHub",
    "Floor": str(Floor),
    "Location": Location,
    "ReportType": "Electricity",
    "System": System,
    "SubSystem": "",
    "Incomer": "",
    "Category": "",
    "DisplayName": DisplayName,
    "Description": Description,
    "Tag": tag,
    "IsActive": 1,
    "DataProviderType": int(0),
    "DataTable": ""
  }
  mydict1.pop("_id", None)
  f.write(str(mydict1) + '\n')



f.close()



回答11:


Platform indepedent line breaker:

import os name = 'bandham'+ os.linesep + 'manikanta' print(name)

Output: bandham manikanta



来源:https://stackoverflow.com/questions/11497376/how-do-i-specify-new-lines-on-python-when-writing-on-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!