Python/기초

[Python] 파일 읽고 쓰기

쇼미요미 2022. 5. 2. 22:12
728x90

안녕하세요. 쇼미요미입니다.

 

오늘은 파일 읽고 쓰기에 대해서 알아보도록 하겠습니다.

 

 

1. 파일 쓰기

f = open("새파일.txt", 'w')   #파일명 입력
f.close()
파일 모드 설명 
r 파일 읽기
w 파일 쓰기
a 파일 마지막에 새로운 내용 추가

 

2. 파일 쓰기모드로 열어 데이터 쓰기

2-1)

f = open("new.txt", 'w', encoding="UTF-8")   #w는 전체 갈아엎기, a는 추가하기
for i in range(1,11):
    data = "%d줄입니다.\n" %i
    f.write(data)
f.close()

2-2)

with open("foo.txt", "w") as f: #f변수에 쓴 텍스트를 foo 파일에 쓴다
    f.write("Life is too short, you need python")
f.close()

 

3. 파일 읽기모드로 열어 한 줄만 출력

f = open("new.txt", 'r', encoding="UTF-8")
line = f.readline()
print(line)
f.close()

 

4. 파일 읽기모드로 열어 모든 라인 출력

4-1)

f = open("new.txt", 'r', encoding="UTF-8")
while True:
    line = f.readline()
    if not line: break
    print(line)
f.close()

4-2)

f = open("new.txt", 'r', encoding="UTF-8")
lines = f.readlines();
for line in lines:
    print(line)
f.close()

 

5. 파일 통채로 읽어오기

f = open("new.txt", 'r', encoding="UTF-8")
data = f.read()
print(data)
f.close()

 

 

728x90