Python - 파일 작성

hanyoko·2023년 7월 11일

PYTHON

목록 보기
11/11
post-thumbnail

파일 생성

open("파일명","모드")
	f= open("test.txt","w",encoding="utf-8")

encoding = "utf-8" 안쓰면 글자가 깨져서 보인다.

w : 쓰기 모드

f = open("test.txt", "w", encoding="utf-8")

f.write("하하하하")
f.close()

test.txt 파일 생성 및 하하하하가 작성된다.

a : 추가 모드

f = open("test.txt", "a", encoding="utf-8")
for i in range(5,9): 
    data = "%d 번째 줄입니다.\n" %i
    f.write(data)
f.close()

r : 읽기 모드*


파일읽기

readline() : 파일의 첫번째 줄 반환

readlines() : 모든 줄을 읽어서 각각의 줄을 요소로 갖는 리스트를 반환

read() : 파일의 내용 전체를 문자열로 반환

d = open('test.txt', 'r', encoding = 'utf-8')

""" readData = d.readlines() #모든줄을 리스트 반환
for i in readData:
    print(i)  """
""" readData = d.readline() # 첫번째 줄만 반환
print(readData)  """

readData = d.read() # 모든 줄을 문자열로 반환
print(readData)   
    
d.close()

예시

***다음과 같은 내용을 지닌 test2.txt파일이 있다
이파일의 내용중 java라는 문자열을 python으로 변경해서 저장하시오
Life is too short
you need java***


#파일 내용 쓰기
f = open('test2.txt', 'w', encoding='utf-8')
data = ("Life is too short\nyou need java")
f.write(data)
f.close()

#파일의 내용을 body변수에 저장
f = open('test2.txt', 'r')
body = f.read()
f.close()

#문자열 변경
body = body.replace("java", "python")

#파일을 쓰기 모드로 실행
f= open('test2.txt', "w", encoding="utf-8")
f.write(body)
f.close()

0개의 댓글