파이썬 파일 write() 메서드
예시
추가를 위해 "a"가 있는 파일을 연 다음 파일에 일부 텍스트를 추가합니다.
f = open("demofile2.txt", "a")
f.write("See
you soon!")
f.close()
#open
and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
정의 및 사용
이 write()
메서드는 지정된 텍스트를 파일에 씁니다.
지정된 텍스트가 삽입되는 위치는 파일 모드와 스트림 위치에 따라 다릅니다.
"a"
: 텍스트는 현재 파일 스트림 위치에 삽입되며 기본값은 파일 끝입니다.
"w"
: 텍스트가 현재 파일 스트림 위치(기본값 0)에 삽입되기 전에 파일이 비워집니다.
통사론
file.write(byte)
매개변수 값
Parameter | Description |
---|---|
byte | The text or byte object that will be inserted. |
더 많은 예
예시
위와 같은 예이지만 삽입된 텍스트 앞에 줄 바꿈을 삽입합니다.
f = open("demofile2.txt", "a")
f.write("\nSee
you soon!")
f.close()
#open
and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())