파이썬에서 파일에 텍스트를 추가하는 방법

Jinku Hu 2023년1월30일
  1. a 모드로 파일에 텍스트를 추가하는 file.write
  2. Python 3의 print 함수에 선택적 file 매개 변수 추가
  3. 텍스트를 파일에 추가 할 때 새 줄 추가
파이썬에서 파일에 텍스트를 추가하는 방법

이 튜토리얼 기사는 파이썬에서 파일에 텍스트를 추가하는 방법을 소개합니다.

a 모드로 파일에 텍스트를 추가하는 file.write

텍스트를 파일에 추가하려면 a 또는 a+모드에서 파일을 열 수 있습니다.

destFile = r"temp.txt"
with open(destFile, "a") as f:
    f.write("some appended text")

위의 코드는 파일의 마지막 문자 옆에 ‘일부 추가 텍스트’텍스트를 추가합니다. 예를 들어, 파일이 ‘이것은 마지막 문장입니다’로 끝나는 경우, 추가 후 ‘이것은 마지막 문장이 추가 된 텍스트입니다’가됩니다.

주어진 경로에 파일이 없으면 파일을 만듭니다.

Python 3의 print 함수에 선택적 file 매개 변수 추가

Python 3에서는 선택적 file 매개 변수를 활성화하여 텍스트를 파일로print할 수 있습니다.

destFile = r"temp.txt"
Result = "test"
with open(destFile, "a") as f:
    print("The result will be {}".format(Result), file=f)

텍스트를 파일에 추가 할 때 새 줄 추가

새 줄에 텍스트를 추가하려면 다음에 추가 된 텍스트가 새 줄에 추가되도록 추가 된 텍스트 뒤에 캐리지 구분\r\n 을 추가해야합니다.

destFile = r"temp.txt"
with open(destFile, "a") as f:
    f.write("the first appended text\r\n")
    f.write("the second appended text\r\n")
    f.write("the third appended text\r\n")
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

관련 문장 - Python File