개발/Python

파일에 쓸 때 파이썬에서 새 줄을 어떻게 지정합니까?

MinorMan 2020. 9. 22. 04:46
반응형

<질문>

Java (문자열)와 비교하여 "First Line \ r \ nSecond Line"과 같은 작업을 수행합니다.

그렇다면 일반 파일에 여러 줄을 작성하기 위해 파이썬에서 어떻게할까요?


<답변1>

얼마나 정확하길 원하는지에 따라 다릅니다. \ n 일반적으로 작업을 수행합니다. 정말로 제대로하고 싶다면 os 패키지에서 개행 문자를 찾아보십시오. (실제로 linesep이라고합니다.)

참고 : Python API를 사용하여 파일에 쓸 때 os.linesep를 사용하지 마십시오. \ n을 사용하십시오. Python은이를 플랫폼에 적합한 개행 문자로 자동 변환합니다.


<답변2>

새 줄 문자는 \ n입니다. 문자열 내부에서 사용됩니다.

예:

    print('First line \n Second line') 

여기서 \ n은 개행 문자입니다.

결과는 다음과 같습니다.

First line
 Second line

Python 2를 사용하는 경우 인쇄 함수에 괄호를 사용하지 않습니다.


<답변3>

새 줄을 개별적으로 작성하거나 단일 문자열 내에 작성할 수 있습니다.

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

'\ n'을 별도로 작성할 수 있습니다.

file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.write("\n")
hello how are you
I am testing the new line escape sequence
this seems to work

다른 사람들이 이전 답변에서 지적했듯이 문자열의 관련 지점에 \ n을 배치하십시오.

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

file.write(line)
hello how are you
I am testing the new line escape sequence
this seems to work

<답변4>

한 번에 여러 줄의 텍스트를 입력하는 경우 가장 읽기 쉬운 형식이라고 생각합니다.

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\
")

각 줄 끝에있는 \는 새 줄을 이스케이프합니다 (오류가 발생 함).


<답변5>

Python에서는 개행 문자 만 사용할 수 있습니다. 예 : \ n


<답변6>

인자없이 print 만 호출하면 빈 줄이 출력됩니다.

print

출력을 다음과 같은 파일로 파이프 할 수 있습니다 (예제 고려).

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

OS와 무관 할뿐만 아니라 (os 패키지를 사용할 필요도 없음) 문자열 내에 \ n을 넣는 것보다 더 읽기 쉽습니다.

print () 함수에는 문자열의 끝을위한 선택적 키워드 인수 인 end가 있으며, 기본값은 OS의 개행 문자입니다. \엔. 따라서 print ( 'hello')를 호출 할 때 Python은 실제로 'hello'+ '\ n'을 인쇄합니다. 즉, 인자없이 print를 호출 할 때 실제로 ''+ '\ n'을 인쇄하여 개행 문자를 생성합니다.

여러 줄 문자열을 사용합니다.

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

<답변7>

플랫폼 독립 회선 차단기 : Linux, Windows 및 IOS

import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)

산출:

physical
distancing

<답변8>

'\ n'과 같은 방식이지만 '\ r'은 필요하지 않을 것입니다. Java 버전에 이유가 있습니까? 필요 / 원한다면 Python에서도 같은 방식으로 사용할 수 있습니다.


<답변9>

\ n-간단한 개행 문자 삽입 작동 :

# 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.....

<답변10>

Java의 문자열 리터럴에있는 대부분의 이스케이프 문자는 "\ r"및 "\ n"과 같이 Python에서도 유효합니다.


<답변11>

다른 답변에서 언급했듯이 "새 줄 문자는 \ n입니다. 문자열 내부에서 사용됩니다".

가장 간단하고 읽기 쉬운 방법은 새 줄의 이름으로 nl을 사용하여 "format"함수를 사용하고 인쇄 할 문자열을 인쇄 할 정확한 형식으로 나누는 것입니다.

python2 :

print("line1{nl}"
      "line2{nl}"
      "line3".format(nl="\n"))

python3 :

nl = "\n"
print(f"line1{nl}"
      f"line2{nl}"
      f"line3")

그러면 다음이 출력됩니다.

line1
line2
line3

이런 식으로 작업을 수행하고 코드의 가독성을 높입니다. :)


<답변12>

대화 형 파이썬 셸 또는 Jupyter 노트북을 사용하여 문자열을 검사 할 때 \ n 및 \ t와 같은 기타 백 슬래시 문자열이 문자 그대로 렌더링된다는 점에 유의할 필요가 있습니다.

>>> gotcha = 'Here is some random message...'
>>> gotcha += '\nAdditional content:\n\t{}'.format('Yet even more great stuff!')
>>> gotcha
'Here is some random message...\nAdditional content:\n\tYet even more great stuff!'

줄 바꿈, 탭 및 기타 인쇄되지 않은 특수 문자는 인쇄되거나 파일에 기록 될 때만 공백으로 렌더링됩니다.

>>> print('{}'.format(gotcha))
Here is some random message...
Additional content:
    Yet even more great stuff!

<답변13>

\ n은 문자열의 줄을 구분합니다. 다음 예에서는 레코드를 루프로 계속 작성합니다. 각 레코드는 \ 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()
반응형