본문 바로가기
Python

[python] 파일 읽고 쓰기

by 남민섭 2023. 3. 7.
728x90
반응형

1. 파일 생성하기

open(파일이름, 파일열기모드)
r ---읽기 모드
w ---쓰기 모드
a ---추가 모드

 

2. 파일읽기

readline() 파일의 첫번째 줄 반환
readlines() 모든 줄을 읽어서 각각의 줄을 요소로 갖는 리스트를 반환
read() 파일의 내용 전체를 문자열로 반환 

 

 

파일 생성(쓰기모드) 실습

*encoding = "utf-8" 안쓰면 글자가 깨져서 보임

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

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

test.txt 파일 생성 및 하하하하가 써짐

test.txt 생성
쓰기모드 사용

실습

#파일 생성/파일 쓰기
f = open("test.txt", "w", encoding="utf-8")
students = ["이나영", "김아랑", "강하늘", "김우리"]
scores = [98,80,77,65]

for i in range(4):
    data = "%s님은 %s 점입니다. \n" %(students[i], scores[i])
    f.write(data)
f.close()   

#파일 읽기
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()

내용 추가하기

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

위에 실습에서 추가 내용

실습(생성/쓰기/추가)

f = open("userText.txt", "w", encoding="utf-8")  #userText 파일 추가 /파일 쓰기
f.close()
while True:
    f = open("userText.txt", "a", encoding = "utf-8") #파일 내용추가 
    userText = input("적고싶은 내용을 작성해 주세요(stop을 누르면 종료합니다.)")
    if userText == 'stop' : break # stop 입력시 종료
    f.write(userText+"\n")
f.close()

useText.txt

실습2

***다음과 같은 내용을 지닌 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()

 

 test2.txt

 

728x90
반응형

'Python' 카테고리의 다른 글

[python] 파이썬 내장함수  (0) 2023.03.07
[python] print함수  (0) 2023.03.07
[python] 함수  (0) 2023.03.07
[python] random 모듈  (0) 2023.03.07
[python] 제어문 - 반복문(for 문)  (0) 2023.03.07

댓글